jQuery Hide and Show Effects
jQuery has a very simple way of achieving some very amazing effects using its methods. These methods allow us to apply some really cool effects with minimal configuration.
Two such methods are:
jQuery hide() and show()
- jQuery hide()
This method hides the element that we want to hide.
Syntax:
$(selector).hide(speed, callback);
- jQuery show()
This method shows the element of html that we want to show.
Syntax:
$(selector).show(speed, callback);
Speed and callback are the parameters passed to these methods defining the speed of hiding and showing and are completely optional.
In speed, the duration can be specified either using one of the predefined string ‘slow’ or ‘fast’, or for greater precision, in milliseconds.
Callback parameter is used after the hiding and the showing function is completed.
JQuery hide()
Method
Let's have a look at an example:
$(document).ready(function(){
$("#hide").click(function(){
//Hide All paragraphs text
$("p").hide();
});
});
Live Demo!
JQuery show()
Method
Let's have a look at an example:
$(document).ready(function(){
$("#show").click(function(){
//If hidden, show all the paragraphs
$("p").show();
});
});
Live Demo!
Implementing the hide()
& show()
functions in an html document:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Learning jQuery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<p>click the "Hide" button, to hide this line
and "Show" button to show.</p>
<button id="test1">Hide</button>
<button id="test2">Show</button>
<script>
$(document).ready(function(){
$("#test1").click(function(){
$("p").hide();
});
$("#test2").click(function(){
$("p").show();
});
});
</script>
</body>
</html>
Live Demo!
JQuery toggle()
Method
jQuery toggle()
method can be used to toggle between hiding & showing of an element. Visible elements get hidden, and the hidden elements get shown.
Syntax:
$(selector).toggle(speed, callback);
The speed parameter is optional, and can have values as 'slow', 'fast' or time can also be passed as milliseconds.
Example:
$(document).ready(function(){
$("#show").click(function(){
$("h1").toggle();
});
});
Live Demo!