We can use jQuery to toggle the visibility of an element by using the jQuery css() method and an if-else statement.
if ( $("#div1").css("visibility") == "hidden" ){
$("#div1").css("visibility","visible");
} else {
$("#div1").css("visibility","hidden");
}
Let’s say I have the following HTML:
This is a paragraph.
If we wanted to use jQuery to toggle the visibility of the paragraph inside of div #div1, we would use the following JavaScript code:
if ( $(".p").css("visibility") == "hidden" ){
$(".p").css("visibility","visible");
} else {
$(".p").css("visibility","hidden");
}
The resulting HTML would be as follows:
If you are using WordPress, don’t forget to change the $ to jQuery as below:
if ( jQuery(".p").css("visibility") == "hidden" ){
jQuery(".p").css("visibility","visible");
} else {
jQuery(".p").css("visibility","hidden");
}
Using jQuery to Toggle the Visibility of a Div with a Click
We can toggle the visibility of an HTML element using jQuery very easily by combining the css() method with a click event.
In this HTML example, we will have two boxes stacked on top of each other. We will provide a button to give the user the option to change the visibility of the top box.
Here is the simple HTML code:
Toggle top box visibility
We can utilize both the jQuery click() method and jQuery css() method to toggle the visibility of the top box. When the user clicks the button, we will run a function that changes the visibility property of the div and changes it to hidden. We will toggle this by using the code we have in the above example.
One thing to notice is when we toggle the visibility of an element it will hide the element from view, but the element will still take up space on the screen. If we want to hide the element and remove it from taking up space on the screen, we would have to target the display property of the element and change it to none.
$("#click-me").click(function(){
if ( $(".box1").css("visibility") == "hidden" ){
$(".box1").css("visibility","visible");
} else {
$(".box1").css("visibility","hidden");
}
});
The final code and output for this example of how to use jQuery to toggle the visibility of a div with a click is below:
Code Output:
Full Code:
Toggle top box visibility
Hopefully this article has been useful for you to understand how to use jQuery to toggle the visibility of an element.