There are a couple of ways we can use jQuery to show and hide a div. The simplest way is to use the jQuery toggle() method.

$("#div1").toggle();

We can also use the jQuery show() and hide() methods to show/hide a div along with an if else conditional statement.

if ( $("#div1").css("display") == 'none' ){
  $("#div1").show()
} else {
  $("#div1").hide();
}

We will use the jQuery toggle() method over other ways to show/hide a div as we find it the easiest one to use.


Let’s say we have the following html:

This is a div that we can show/hide with jQuery

If we want to use jQuery to show/hide the div, we can do so by using the jQuery toggle() method.

$("#div1").toggle();

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

jQuery("#div1").toggle();

Note that we can also show/hide (or toggle) a div easily using plain JavaScript by targeting an element’s display property.

Using jQuery to Show/Hide a Div With a Click

We can use jQuery to show and hide a div very easily by combining the toggle() method with the click() method.

Let’s say that we have the following HTML where we want to give the user the ability to show and hide the div #div1. The div will just be a greenish box that will be shown to start.

Here is the HTML code:



Show/hide

In the JavaScript code, when a user clicks the button, we will run a function that we will create. In the function, we will simply apply the toggle method to the div, which will hide it if it is shown, or show the div if it is hidden.

Here is the JavaScript code:

$("#click-me").click(function(){
  $("#div1").toggle();
}); 

The final code and output for this example of how to show/hide a div using jQuery is below:

Code Output:

Show/hide

Full Code:


Show/hide

Hopefully this article has been useful for you to understand how to use jQuery to show/hide a div.

Categorized in:

jQuery,

Last Update: February 26, 2024