jQuery toggle() Effect

The jQuery toggle() effect is used to show /hide each of the selected elements. It shows each of the selected elements which are disabled and hides each of the selected elements which are shown.

Syntax of toggle() Effect

$(selector).toggle(speed, callback) 

The selector is the element which to be hidden or shown. Both speed and callback parameters are optional. The speed parameter specifies either in milliseconds or a few predefined strings, slow and fast. The callback function is called after the element completely hidden or displayed.

Example

<style>
.cls { display: none;}
</style>
<p id="demo" class="cls"> Hello World!</p>
<button id="btn">Hide/Show Text</button>

<script>
$(document).ready(function(){
$("#btn").click(function() {
$("#demo").toggle();
});
});
</script>

Output of the above code

Hello World!


In the above example, when the user click on the 'Hide/Show Text' button, the paragraph of 'demo' id get hidden.


Example - toggle() with time and callback function

<style>
.demobox { 
width: 200px; 
height: 150px; 
background-color: pink;
padding: 20px;
border: 4px solid black;
display: none;
}
</style>

<div id="demo" class="demobox"> Demo Box</div>
<br/>
<button id="btn">Toggle Box</button>

<script>
(function( $ ) { 
$("button#btn").click(function() {
$("div#demo").toggle("slow", function() {
alert( "Toggle effect occurred." ););
});
});	
})(jQuery);
</script>

Output of the above code

Demo Box

In the above example, when the user click on the 'Toggle Box' button, the div box of 'demo' id get displayed or hidden.



Read more articles


General Knowledge



Learn Popular Language