21
Aug
2012

Show Hide a region using jQuery

jquery_logo

We have already discussed jQuert show(), hide() and toggle() methods to show, hide and toggle a target region. This tutorial is little different as it will also toggle the link text.

Step 1:
Prepare a DIV region with some text under ID #message
Also add a link which will toggle (Show / Hide) the #message region.

<a id="showhide" href="#">Hide</a>
<div id="message">Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</div>

Step 2:
Call jQuery library. I am using Google CDN hosted jQuery library.
You can use alternative method to include jQuery library.

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

Step 3:
Now add following jQuery code

<script type="text/javascript">
$(document).ready(function() {
$("#showhide").toggle(function() {
	$("#showhide").text('Show');
	}, function() {
	$("#showhide").text('Hide');
	});
$("#showhide").click(function() {
	$("#message").toggle();
});
});
</script>

Explanation of above jQuery code


When the link under ID #showhide is clicked, it will toggle text show and hide.

And we added another function, When the link under ID #showhide is clicked, it will toggle (show / hide) region under ID #message.


Done!!!
Check demo

We can rewrite same jQuery code like this also:

<script type="text/javascript">
$(document).ready(function() {
$("#showhide").toggle(function() {
	$("#showhide").text('Show');
	$("#message").hide();
	}, function() {
	$("#showhide").text('Hide');
	$("#message").show();
	});
});
</script>

Check demo

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