jquery toggle()
The toggle() method is used to toggle between show and hide selected HTML elements. If elements are hidden then toggle method will show hidden selected elements and vice versa.
Syntax
$(selector).toggle(speed,callback)
Where
Selector = can be an element like div, p, etc.
Speed = Optional parameter that specifies the hide speed with possible values of
- “slow”
- “fast”
- Or value in milliseconds
Callback = after togle () method is completed, an optional callback function to perform certain action can be given.
Example of toggle() method
In this example we will use jquery hide method to toggle DIV with name “text” after clicking “Toggle Yellow line” button.
Experience this example online
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
29
30
31
32
33
34
35
36
37
|
<!DOCTYPE html>
<head>
<title>jQuery Testing</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$(".hidetext").click(function () {
$(".text").toggle("slow")
});
});
</script>
</head>
<body>
<button class="hidetext">Toggle yellow line</button>
<div class="text" style="background-color:yellow;display: none;">
This is Yellow line!!
</div>
</body>
</html>
|
Example with callback function
Experience this example online
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
29
30
31
32
33
34
35
36
37
38
39
40
41
|
<!DOCTYPE html>
<head>
<title>jQuery Testing</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$(".hidetext").click(function () {
$(".text").toggle("slow",function(){
alert("Toggle method executed");
});
});
});
</script>
</head>
<body>
<button class="hidetext">Toggle yellow line</button>
<div class="text" style="background-color:yellow;display: none;">
This is Yellow line!!
</div>
</body>
</html>
|
Also see: jquery show() method | jquery hide() method
Leave A Comment?