There are a couple of ways we can use jQuery to hide a div. The simplest way is to use the jQuery hide() method.
$("#div1").hide();
We can also use the jQuery css() method to hide a div.
$("#div1").css("display", "none");
Hiding a div using jQuery is very easy using the hide() method.
Let’s say I have the following html:
This is a div that I can hide with jQuery
Next, we want to hide the div, so we will use the jQuery hide() method. If we wanted to hide the div when the web page initially loads the JavaScript file, it would look like:
$(document).ready(function() {
$("#div1").hide();
});
If you are using WordPress, don’t forget to change the $ to jQuery as below:
jQuery("#div1").hide();
Another way you can hide a div using jQuery is to use the jQuery css() method:
$("#div1").css("display", "none");
The jQuery css() method is very useful for changing the styling of a html element dynamically – for example, changing the background color of a div.
Note that we can also hide a div in just plain JavaScript using the display property.
Using jQuery to Hide a Div With a Click
We can use jQuery to hide a div very easily by combining the hide() method with a click event.
Let’s say that we have the following html where we want to give the user the ability to hide “Div 1”:
Div 1
Div 2
Hide Div 1
We can utilize both the jQuery click() method and jQuery hide() method to hide “Div 1”.
Below is the JavaScript code which will allow the user to be able to hide “Div 1”:
$("#click-me").click(function(){
$("#div1").hide(); // Results in the element #div1 being hidden
});
The final code and output for this example of using jQuery to hide a div with a click is below:
Code Output:
Full Code:
Div 1
Div 2
Hide Div 1
Using the jQuery css() Method to Hide a Div
The jQuery css() method is incredibly useful when using JavaScript to manipulate web pages.
We can use the css() method to easily hide a div.
Let’s say that we have the following html (the same as above) where we want to give the user the ability to hide the shown “Div 1”:
Div 1
Div 2
Hide Div 1
We will utilize both the jQuery click() method and jQuery css() method to hide “Div 1”.
Below is the JavaScript code which will allow the user to be able to hide “Div 1”:
$("#click-me").click(function(){
$("#div-1").css("display","none"); // Results in the element #div-1 being hidden
});
The final code and output for this example of how to hide a div using the jQuery css() method is below:
Code Output:
Full Code:
Div 1
Div 2
Hide Div 1
Hopefully this article has been useful for you to understand how to use jQuery to hide a div.