02
May
2012

jQuery Toggle

Posted in: jQuery , No Comments

jquery_logo
jQuery Toggle is used to toggle a region. In simple words we can say it is used to show and hide a selected element / region. The toggle() method toggles between hide() and show() for the selected region / elements.

Syntax

$(selector).toggle(speed)

Speed can be:

1. slow
2. fast
3. In milliseconds like 4000

Below example will help you understand jQuery toggle easily.
Step 1: Prepare basic HTML page

<!DOCTYPE html>
<html>
<title>jQuery Toggle</title>
<head></head>
<body>
<button class="mybutton">Click Me to Toggle</button>
<div id="mytoggle">
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.
</div>
</body>
</html>

Step 2: Add used CSS styles in head section.

<style type="text/css">
#mytoggle {
background: #d1d1d1;
text-shadow: 1px 1px #fff;
padding: 10px;
border-radius: 7px;
}
</style>

Step 3: Add jQuery library in head section.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

Step 4: Add jQuery toggle code in head section.

<script type="text/javascript">
$(document).ready(function(){
    $("button.mybutton").click(function(){ // declare a new function for click action.
    $("#mytoggle").toggle(); // this will show / hide content of region #myexpand
    });
});
</script>

Step 5: So, our final code is:

<!DOCTYPE html>
<html>
<title>jQuery Toggle</title>
<head>
<style type="text/css">
#mytoggle {
background: #d1d1d1;
text-shadow: 1px 1px #fff;
padding: 10px;
border-radius: 7px;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $("button.mybutton").click(function(){ // declare a new function for click action.
	$("#mytoggle").toggle(); // this will show / hide content of region #myexpand
	});
});
</script>
</head>
<body>
<button class="mybutton">Click Me to Toggle</button>
<div id="mytoggle">
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.
</div>
</body>
</html>

Demo

You can now modify this effect with slow or fast speed.

About the Author

Name: Ravi Shekhar
I love learning and sharing web stuffs.

Share this post

Twitter Facebook Google Buzz Digg StumbleUpon Delicious Technorati

Leave a Reply