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>
<script>
function changeOpacity() {
var image = document.getElementById("myImage");
var currentOpacity = image.style.opacity;
if (currentOpacity == 1) {
image.style.opacity = 0.5;
} else {
image.style.opacity = 1;
}
}
</script>
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
.
+ There are no comments
Add yours