Learn and share. The simplest harmony.

 

[Code Snippet] jQuery : Show/Hide Element

Posted on March 9, 2010 and got 5 shouts so far

This is a very basic technique to show and hide HTML element, we just need to define the element then show or hide them with jQuery built-in function, $.slideToggle(). But if you see my sidebar in ‘Tags Collection’ section, you’ll notice that there’s a toggle to show or hide the tags collection (with undefined div’s height, of course) and that’s what i will explain.

First we make up the html :

.list-tag {
	height: 195px;
	overflow: hidden;
}

.more-tags {
	cursor: pointer;
	padding-top: 15px;
	background: url('shade-tag.png') center top no-repeat;
	display:block;
	text-align: center;
}

Div list-tag is a div binder of div content-list-tag, the div content-list-tag has undefined height whilst the div binder has the pre-defined height, based on our needs. Div more-tags is a toggle to show or hide the div content-list-tag.

First we must inject div more-tags with $.toggle() function to make it toggled, read the div content-list-tag’s height by $.height() function, show the div content-list-tag’s content by animating it then rotate the down.png image to 180deg (we need a jquery plugin to do this step). If the user click the toggle once more, then we just need to revert previous step.

$('.more-tags').toggle(function() {

	contentTagsHeight	= $('.content-list-tag').height();

	$('.list-tag').animate({height : contentTagsHeight});
	$(this).children('img').animate({rotate: '180deg'});

}, function() {

	$('.list-tag').animate({height : '195px'});
	$(this).children('img').animate({rotate: '0deg'});

});

 

This Post Tags :

Bookmark Post :

Pin It
  • Thanks for posting this! It is exactly what I needed.

  • Thanks a bunch for sharing the snippet!

  • How does the script know to set the “list-tag” height to “0″? Does the height set in the style sheet have to match the height set in the script?

    Thanks for your tutorial!!

  • I set the script height to “0″ and now it seems to work. How about if I want the element hidden first? Should I set the style sheet to “0″ and the script to my desired opened height?

    • David,

      You should set the stylesheet to “0″ or animate the height to “0″ using script, but I suggest set the height using script rather than stylesheet just in case the jQuery doesn’t loaded, so the content in “list-tag” will remain visible.