In this tutorial we will learn How to change Image opacity with JavaScript. For this we can use JavaScript style property with which we can change value of the opacity of image to any value.
Table of Contents
style property
style property returns the CSSStyleDeclaration object which contains all CSS inline properties of an HTML element.
In this example it is used to change the opacity of img tag.
HTML Code
HTML Code is given below, in this code we have img tag, input tag and a button tag with onclick event which is used to execute a JavaScript function.
<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript Change image opacity</title>
<style>
.responsive
{
width: 100%;
}
</style>
</head>
<body>
<img src="car.jpg" id='image' class="responsive">
<input type="text" id="opacity" placeholder="0 to 1">
<br><br>
<button onclick="changeOpacity()">Change Opacity</button>
<script src="script.js"></script>
</body>
</html>
JavaScript Code
Take a look at the JavaScript code, in this code getElementById() method is used to select or target the image.
Then JavaScript value property is used to read the value of opacity from the user.
In the end style property changes the opacity of image.
<script>
function changeOpacity()
{
var image = document.getElementById("image");
var opacity = document.getElementById("opacity").value;
image.style.opacity = opacity;
}
</script>
We can also change the opacity to the fixed or static value defined in the code, look at the example below.
<script>
function changeOpacity()
{
var image = document.getElementById("image");
var opacity = 0.5;
image.style.opacity = opacity;
}
</script>
Demo
Video Tutorial
Watch video tutorial on How to change Image opacity with JavaScript.