How to change image opacity using JavaScript?

Estimated read time 1 min read

You can change the opacity of an image in JavaScript by modifying its style.opacity property. The value of opacity should be between 0 and 1, where 0 is completely transparent and 1 is completely opaque.

Here’s an example that changes the opacity of an image with id “myImage”:

<img id="myImage" src="image.jpg" style="opacity: 1">

<button onclick="changeOpacity()">Change Opacity</button>

  function changeOpacity() {
    var image = document.getElementById("myImage");
    var currentOpacity =;
    if (currentOpacity == 1) { = 0.5;
    } else { = 1;

In this example, the changeOpacity function is called when the “Change Opacity” button is clicked. The function uses getElementById to select the image with id “myImage”. Then, it checks the current value of the opacity property, and if it’s 1, it sets it to 0.5. If it’s not 1, it sets it back to 1.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply