Changing an elements visibility with jQuery

Adjusting the visibility of element within a web page comes in handy from time to time for features like tool tips, extending content after a short excerpt etc. This technique adds greatly to the user experience of your site and has been around for a long time but the jQuery library makes this task a lot easier with the hide method.

To get started if you haven’t already load the jQuery library into the head of your page i.e

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

Then create the element you would like to hide, in this example I am just going to hide a simple div when a anchor is clicked.

<script type="text/javascript">
$("#hide").click(function(){
     $("#some_content").hide();
});
</script>

<a href="#" id="hide">Hide</a>
<div id="some_content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin lacus libero, dapibus eget dictum in, laoreet non massa. Aliquam nec felis tellus, quis ullamcorper erat.
</div>

This works well for hiding the content contained within the element but what if the user accidentally clicked the hide link? They would have to reload the page to be able to see the content again, to avoid this sometimes it is better to use the jQuery toggle method instead allowing the user to change the visibility of the element back and forth.

<script type="text/javascript">
$("#hide").click(function(){
     $("#some_content").toggle();
});
</script>

<a href="#" id="hide">Change visibility</a>
<div id="some_content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin lacus libero, dapibus eget dictum in, laoreet non massa. Aliquam nec felis tellus, quis ullamcorper erat.
</div>

Leave a Reply

Your email address will not be published.