Difference Between show(), hide() and toggle() function in jQuery

By | 02/06/2012

In jQuery programming, show() function is to show the html element and hide() function is to hide the html element. toggle() function also do the same operation. Many jQuery newbie programmers gets confused about the difference between show(), hide () and toggle()

The difference between show(), hide() and toggle() is toggle() function do the action of both show and hide.

show() & hide()

Here is the example for show() and hide() function. We can reduce or increase the speed of shoe and hide action by following options

hide()

$(“div.text”).hide();   -No argumented hide() will hide the <div> fastly
$(“div.text”).hide(“slow”);   – This hides the <div> element very slowly and smoothly
$(“div.text”).hide(“fast”);   – Hides <div> element fastly
$(“div.text”).hide(“1200″);  - Based on our choice , <div> element will be hided

show()

$(“div.text”).hide();   -No argumented show() will shows the <div> fastly
$(“div.text”).hide(“slow”);    - This shows the <div> element very slowly and smoothly
$(“div.text”).hide(“fast”);   – shows <div> element fastly
$(“div.text”).hide(“1200″);   – Based on our choice , <div> element will be shown

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#hide").click(function(){
$("div.text").hide();
});

$("#slow").click(function(){
$("div.text").show();
});
});
</script>
</head>
<body>

<div class="text" style="background-color:#999; height:200px; width:250px;">
Example for show and hide
</div>
<a href="#" id="hide">Hide</a>

<a href="#" id="slow">Show</a>

</div>
</body>
</html>

 

toggle()

toggle() function can do both show and hide actions. Some of the options on toggle() are

$(“div.text”).toggle(); -No argumented toggle() will shows and hides the <div> fastly
$(“div.text”).toggle(“slow”); – This shows and hides the <div> element very slowly and smoothly
$(“div.text”).toggle(“fast”); – shows and hides <div> element fastly
$(“div.text”).toggle(“1200″); – Based on our choice , <div> element will be shown and hidden

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#but").click(function(){
{
$("div.text").toggle();
}
});
});
</script>
</head>
<body>
<div class="text" style="background-color:#999; height:200px; width:250px;">
Example for toggle
</div>
<a href="#" id="but">Click</a>
</div>
</body>
</html>

 

prasad

About prasad

Prasad K has written 111 post in this blog.