Categories
JavaScript Answers

How to Change Image Opacity Using JavaScript?

Spread the love

Sometimes, we want to change image opacity using JavaScript.

In this article, we’ll look at how to change image opacity using JavaScript.

Change Image Opacity Using JavaScript

To change image opacity using JavaScript, we can set the style.opacity and style.filter properties of the img element to the value we want.

For instance, if we have:

<img src='https://picsum.photos/200/300'>

Then we write:

const element = document.querySelector('img');
element.style.opacity = "0.5";
element.style.filter = 'alpha(opacity=90)';

to select the img element with document.querySelector.

Then we set the style.opacity property of element to 0.5 to set the CSS opacity property value.

Likewise, we set the style.filter property of element to 'alpha(opacity=90)' to set the CSS filter property value.

Now we should see the opacity and filter values applied to the image.

Conclusion

To change image opacity using JavaScript, we can set the style.opacity and style.filter properties of the img element to the value we want.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *