How to change Image opacity with JavaScript

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.

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.

Change font-size using JavaScript Get Font Size of any Tag using JavaScript Change Position of HTML Element using JavaScript How to Change Image on Hover with JavaScript How to Disable Button by Class Name in JavaScript How To Change Image Size with JavaScript How to change Image opacity with JavaScript How to Change image src on click with JavaScript How to get the lang attribute value in JavaScript How to Get attribute Value using JavaScript How To Check if Attribute Exists or not with JavaScript How To Count number of links on Page with JavaScript How To Scroll Page to Bottom using JavaScript How To Detect Shift Key Press with JavaScript Change Text Color On Hover with JavaScript Hide and Show div using JavaScript Get Button text with JavaScript Get textarea value with JavaScript Get table row Height with JavaScript Auto Increase width of input field with JavaScript Set Textarea maxLength with JavaScript Set Textarea Value with JavaScript JavaScript Count list items JavaScript set input field value Count Button Clicks with JavaScript Scroll Page to the Top on Click with JavaScript