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 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.
Conclusion
To change image opacity using JavaScript, we can use the setAttribute
method.