Categories
JavaScript Answers

How to Change Image Opacity Using JavaScript?

Spread the love

To change image opacity using JavaScript, we can use the setAttribute method.

For instance, if we have the following image:

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

We write:

document
  .querySelector("img")
  .setAttribute("style", "opacity:0.5; -moz-opacity:0.5; filter:alpha(opacity=50)");

to select the img element with document.querySelector("img").

Then we call setAttribute with 'style' and "opacity:0.5; -moz-opacity:0.5; filter:alpha(opacity=50)" to set the style attribute of the img element to opacity:0.5; -moz-opacity:0.5; filter:alpha(opacity=50).

Therefore, we see that the resulting image displayed is translucent.

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 *