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:
<style>#div1 { background: green; }</style>
<div id="div1">
<p>This paragraph is in a div that we want to change the opacity of.</p>
</div>
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.
<style>#div2 { width: 300px; height: 200px; background: #7bbfa2; }</style>
<div id="div1">
<div id="div2"></div>
<div id="click-me" onclick="changeOpacity()">Change opacity</div>
</div>
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:
<style>#div2 { width: 300px; height: 200px; background: #7bbfa2; }</style>
<div id="div1">
<div id="div2"></div>
<div id="click-me" onclick="changeOpacity()">Change opacity</div>
</div>
<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.
Leave a Reply