There are many ways to use jQuery to change the opacity of an element. We can do this by using the jQuery fadeTo() method or the jQuery css() method.

Here is an example using the jQuery fadeTo() method:

$("#div1").fadeTo(1000, .5);

Here is an example using the jQuery css() method:

$("#div1").css("opacity", ".5");

The main difference between these two methods is that the fadeTo() method will change the opacity over a given duration(400 milliseconds is the default).

If you changed the duration to 0 milliseconds, the fadeTo() method should work the same as the css() method. The jQuery css() method will target the opacity property of an element. Moving forward, we will use the jQuery css() method to change the opacity of an element.


Let’s say we have the following HTML:


This is some div

If we want to change the opacity of #div1, we can use the jQuery css() method to target the opacity of the div.

$("#div1").css("opacity", ".2");

The above code would change the opacity of #div1 to .2.

If you are using WordPress, don’t forget to change the $ to jQuery as below:

jQuery("#div1").css("opacity", ".2");

Let’s see this in action in the example below.

Using jQuery to Change the Opacity of a Div with a Click

In this simple example, we will have a div with a greenish background. We will provide a button for the user to use to change the div’s opacity.


Change opacity

We can utilize both the jQuery click() method and jQuery css() method to change the opacity.

Below is the JavaScript code which will allow the user to change the opacity of the div. We will change the div to have an opacity of .2(barely visible):

$("#click-me").click(function(){
  $("#div2").css("opacity", ".2");
});

The final code and output for this example of using jQuery to change the opacity of a div is below:

Code Output:

Change opacity

Full Code:


Change opacity
<script> $("#click-me").click(function(){ $("#div2").css("opacity", ".2"); }); </script>

Hopefully this article has been useful for you to understand how to use the jQuery css() method to change the opacity of an element.

Categorized in:

jQuery,

Last Update: February 26, 2024