Use your left/right keys to browse tutorials
jQuery Show / Hide Plugin

jQuery Show / Hide Plugin

1 Star2 Stars3 Stars4 Stars5 Stars
Posted on September 28, 2011

Due to popular demand here’s a re-written version of the tutorial I wrote over a year ago on how to show and hide content using jQuery. After I first published the post I’ve had a lot of requests as to how you can show and hide multiple divs so I’ve written this plugin which does all the work for you!

The Plugin

(function ($) {
    $.fn.showHide = function (options) {

	//default vars for the plugin
        var defaults = {
            speed: 1000,
			easing: '',
			changeText: 0,
			showText: 'Show',
			hideText: 'Hide'

        };
        var options = $.extend(defaults, options);

        $(this).click(function () {
// optionally add the class .toggleDiv to each div you want to automatically close
                      $('.toggleDiv').slideUp(options.speed, options.easing);
			 // this var stores which button you've clicked
             var toggleClick = $(this);
		     // this reads the rel attribute of the button to determine which div id to toggle
		     var toggleDiv = $(this).attr('rel');
		     // here we toggle show/hide the correct div at the right speed and using which easing effect
		     $(toggleDiv).slideToggle(options.speed, options.easing, function() {
		     // this only fires once the animation is completed
			 if(options.changeText==1){
		     $(toggleDiv).is(":visible") ? toggleClick.text(options.hideText) : toggleClick.text(options.showText);
			 }
              });

		  return false;

        });

    };
})(jQuery);

The Usage

Here we setup the options for the plugin. you can set the speed of the toggle, if you include the jQuery UI plugin you can specify an easing effect. Also there’s an option to change the text for the button. 1 is change 0 is dont change. and the final options are the show and hide text.


$(document).ready(function(){

   $('.show_hide').showHide({
		speed: 1000,  // speed you want the toggle to happen
		easing: '',  // the animation effect you want. Remove this line if you dont want an effect and if you haven't included jQuery UI
		changeText: 1, // if you dont want the button text to change, set this to 0
		showText: 'View',// the button text to show when a div is closed
		hideText: 'Close' // the button text to show when a div is open

	});

});

The HTML

Here you can see the simple usage for the plugin. We’ve already set the plugin options above in our DOM ready function now here we set our divs up. for element you want to toggle, you just need to add the div id to the rel attribute of the a tag as shown below. You can now add as many show hide divs as you want to.

If you want all the open divs to close when you click to open another simply add the class .toggleDiv to each element.

 <a class="show_hide" href="#" rel="#slidingDiv">View</a></pre>
<div id="slidingDiv" class="toggleDiv" style="display: none;">Fill this space with really interesting content.</div>
<pre>
 <a class="show_hide" href="#" rel="#slidingDiv_2">View</a></pre>
<div id="slidingDiv_2" class="toggleDiv" style="display: none;">Fill this space with really interesting content.</div>
<pre>

download



More tutorials from Papermashup
Comments
156 discussions around jQuery Show / Hide Plugin
Older Comments
  1. bala says:

    Hi friend, plz could you give me idea, how to move horizontal.

    Thanks,

  2. Using rel=”#slidingDiv” in your markup will cause the following validation error:

    “Bad value #slidingDiv for attribute rel on element a: The string #slidingdiv is not a registered keyword or absolute URL.”

    - http://validator.w3.org/

    An alternative is to use data-link=”#slidingDiv”.

    In the script change:

    var toggleDiv = $(this).attr(‘rel’);

    To this:

    var toggleDiv = $(this).attr(‘data-link’);

  3. Works very well. Thank you.

  4. Rus says:

    Thanks for the tutorial. Works great in Chrome but not in IE8. The divs do not display as they should. Does anyone know why this could be or has a fix to this?

    • Rus says:

      Found a fix. It seems IE does not like the , (comma) before closing curly brace. See the example below. I removed the comma after easing: ”

      $(document).ready(function(){
      $(‘.show_hide’).showHide({
      speed: 400, // speed you want the toggle to happen
      easing: ” // the animation effect you want
      });
      });

  5. Patrick says:

    Hey! How do I get these to stay collapsed on load? They are all open when the page loads

  6. Eliezer says:

    I’m trying to replace the add and hide text with images, but It won’t work. How can this be done?

  7. Bryan says:

    The code works really well, it’s exactly what I wanted for my website, and I appreciate the help since I don’t know Javascript coding yet. The only problem I’m running into is browser issues. It works in safari, google chrome and even android OS but when I use it in internet explorer or mozilla firefox the div doesn’t expand when you click ‘view’. Is there a piece of code that I’m missing?

  8. Louis says:

    Where do I put the code from the section ‘The Usage’?
    In the qs file or somewhere in the website?

    Sorry, no experience with adding JQueries at all…

    Thanks!

    • Louis says:

      Please ignore my previous message.

      I have added the js file and the code to a wordpress page, however I can’t get the script working. Can someone please help me out?

      Thanks!

Older Comments




Never miss an update from Papermashup

Get notified about the latest tutorials and downloads.

Subscribe by Email

Get alerts directly into your inbox after each post and stay updated.
Subscribe
OR

Subscribe by RSS

Add our RSS to your feedreader to get regular updates from us.
Subscribe

Get in contact

Please use the form below to get in contact. If your question is related to a free script download, please use the comments on the article page as community members are more likely to respond quicker than I can personally.

About Me

I'm Ashley Ford, Co-founder and Technical Director at Harkable.com London, UK. Previously I worked at InMobi, Spotify and MySpace. My interests include photography and making short videos I'm also an avid F1 fan. I'm always working on side projects. Here are a few: Easy Poll, We Deliver.



What do you specialise in?

I spend a lot of time coding in PHP and MySQL, as well as front end XHTML and CSS. I also specialise in javascript and the jQuery framework as well as being an avid designer. You can find me on dribbble

Interested in advertising?

If you'd like to advertise on Papermashup.com please get in touch via the contact link below for advertising opportunities.

How do I contact you

You can contact me here. and I'm available for consultation, freelance, programming book reviews.

Get on the mailing list

Join over 3000 people who have subscribed to the Papermashup inbox message, and be the first to find out about tutorial, competitions and giveaways.