In JavaScript, we can change the opacity of a div simply by using the CSS opacity property along with the getElementById() method.
document.getElementById("div1").style.opacity = .2;
Let’s say we have the following HTML:
This paragraph is in a div that we want to change the opacity of.
If we want to change the opacity of #div1 to be semi-transparent, we will use the opacity property in the following JavaScript code.
document.getElementById("div1").style.opacity = .5;
Using JavaScript to Change the Opacity of a Div with a Click
To change the opacity of a div using JavaScript, we can target the CSS opacity property with an onclick event.
Let’s say we have the following HTML and we want to change the opacity of #div2 to .2.
We can utilize both the opacity property of #div2 along with an onclick event to change the opacity.
Below is the JavaScript code which will allow the user to be able to change the opacity of #div2:
function changeOpacity() {
document.getElementById("div2").style.opacity = .2;
}
The final code and output for this example of how to change the opacity of our div using JavaScript is below:
Code Output:
Full Code:
<script>
function changeOpacity() {
document.getElementById("div2").style.opacity = .2;
}
</script>
Hopefully this article has been useful for you to understand how to use JavaScript to change the opacity of an element.