Basic Show and Hide

read 53 comments

As promised in my last entry, I'll be showing you a simple effect that you can do using jQuery: showing or hiding something, or a group of things, on the page. The two functions that let us do this are, not surprisingly, show() and hide().

jQuery also comes with another function called toggle(), which will make matching elements visible if they are hidden or hidden if they are visible.

So, let's get down to business. We're going to start with our $(document).ready() function.

JavaScript:
  1. $(document).ready(function() {
  2.   // we'll put our code here
  3. });

Next, we'll choose what we want to show or hide. Hmm, let's see. How about the site's title? Excellent! Now, whenever we refer to an element in jQuery, we start with the dollar sign, $, and we put any CSS or XPATH selector in parentheses right after it:

$('css-selector')

Since the site's title is wrapped in an <h1> tag, we'll refer to it this way: $('h1'). We could just as easily refer to all DIVs with a class of "treacle" — $('div.treacle') — or any paragraph that is a chlid of a DIV with an ID of "bonespur" — $('#bonespur > p').

Now for the magic. To make the site's title disappear, we just connect $('h1') and hide() with a dot (.) and stick it all inside the $(document).ready() like so:

JavaScript:
  1. $(document).ready(function() {
  2.   $('h1').hide();
  3. });

The code above will make the site's title hide when the DOM / page loads, which isn't ideal for our purposes here, so I'm going to attach the the hide() event to the first button below instead. The second and third buttons will handle show() and toggle() respectively.

Just for kicks, we'll show and hide this sentence, which is wrapped in a div with class="showhide", too.

How did I attach the hiding and showing to those buttons? I'll show you that in my next entry.

comment feed

53 comments

  1. Aunt Ginny

    Well, Karl, this level of geekdom is awesome but way beyond my comprehension! Very esoteric! Good for youse guys!

  2. sam

    is there a zip file contain of these code ?

  3. Steph

    Thanks for this helpful intro Karl, I downloaded jquery today ... I'v been struggling with some of the documentation.

  4. tag hag

    thanks, these tutorials have been really helpful to me. i have a little question, perhaps it's already covered somewhere else, but i was wondering if it's still necessary to put return false in mouseover and click events like is often required in javascript? or does the library take care of this automatically?

  5. You only need to use return false if you are binding an onclick handler to an element that has a default behavior. For example, links (<a href="something"></a>) have a default behavior, so you would put return false; inside the .click() method, after the code that says what you really want the click to do. However, if you're attaching .click() to an <h3>, there is no need to return false. Let me know if you'd like me to clarify any of this.

  6. Excellent posts. I've been having a bit of a hard time trying to figure out how to implement a bunch of this stuff but your posts have really made it easy to begin to wrap my mind around concepts and practices.

  7. Luke Robinson

    In the last example, I think you meant to type "class="showhide".

    Just for kicks, we'll show and hide this sentence, which is wrapped in a div with class="showide", too.

  8. Yep, you're right, Luke. Good catch! And thanks for reporting it. I've fixed the typo.

  9. Dave

    Hey,
    Shouldn't the title of your page disappear when the page loads? It only actually seems to be tied to the buttons - and not document ready as the example suggests.

    Also, I'm having a problem with this kind of thing in Firefox - I want an element to be hidden by default - so I put .hide in a document.ready function. Then I show the element with a button - but firefox seems to raise a 'page ready' event again, causing the element to be hidden almost as soon as it's displayed.

    Any ideas?

  10. Hi Dave,
    No, the title shouldn't disappear when the page loads.

    The code above will make the site's title hide when the DOM / page loads, which isn't ideal for our purposes here, so I'm going to attach the the hide() event to the first button below instead. The second and third buttons will handle show() and toggle() respectively.

    So, in other words, I did something like this:

    $(document).ready(function() {
      $('#hideh1').click(function() {
        $('h1').hide();
      });
    });

    I'll need to see your code before I can help you with the problem you're describing. Can you send me a link to a web page somewhere?

  11. Great .. direct and simple.. thanks

  12. dickbob

    How can I test the current show/hide status so that I can change the value of the toggle button to display "show" or "hide" as appropriate?

  13. You should definitely take a look at some of the other tutorials on this site.

    You could use .toggle() or .slideToggle(). You could also use ":visible" or ":hidden" in a conditional statement, like so:

    if ($('h1').is(':visible')) {
        $('h1').hide();
    } else {
        $('h1').show();
    }

    There are many ways you could do this, and many of them are explained on this site.

  14. dickbob

    Thanks for that Karl. Spot on!

    I'm early in my jQuery journey so I haven't had a chance to read all your fine tutorial just yet, but I will!

  15. Scott

    I've found the same issue that Dave posted. Using the toggle function in jquery 1.2.3 has a bug with Firefox (2.0.0.12). Perhaps it's a bug. Toggel seems to function in IE and safari fine, but Firefox closes the element immediately upon showing it.

    I initially thought it may be the easing plug in causing the bug, but after removing all easing code it still exists.

    My code:

    $("#infostuff").hide();

    $("#info a").toggle(
    function () { $("#infostuff").animate({ height: "show" }, 700, "easeInQuad"); return false; },
    function () { $("#infostuff").animate({ height: "hide" }, 700, "easeOutQuad"); return false; }
    );

    I've temporarily gotten around the issue by eliminating the toggle completely and just adding a click function with a secondary link to close the content, but I'd really like a toggle.

    Any help at all is greatly appreciated. I'm a designer far more than a programmer.

  16. Scott

    I've found the same issue that Dave posted. Using the toggle function in jquery 1.2.3 has a bug with Firefox (2.0.0.12). Perhaps it's a bug. Toggel seems to function in IE and safari fine, but Firefox closes the element immediately upon showing it.

    I initially thought it may be the easing plug in causing the bug, but after removing all easing code it still exists.

    My code:

       
    $("#infostuff").hide();
    $("#info a").toggle(
        function () { $("#infostuff").animate({ height: "show" }, 700, "easeInQuad"); return false; },
        function () { $("#infostuff").animate({ height: "hide" }, 700, "easeOutQuad"); return false; }
     );
    
    

    I've temporarily gotten around the issue by eliminating the toggle completely and just adding a click function with a secondary link to close the content, but I'd really like a toggle.

    Any help at all is greatly appreciated. I'm a designer far more than a programmer.

  17. Hi Scott,

    Unfortunately, bug tracking and fixing is beyond the scope of this blog. I think your best bet for a solution to this problem would be to contact the jquery-dev mailing list. If you could provide a simple test-case URL for them, that would be very helpful.

    In the meantime, you could use a simple .click() and test for the visibility of $('#infostuff'), like so:

    var $infostuff = $("infostuff");
    $("#info a").click(
        function () {
          if ($infostuff.is(":hidden")) {
            $infostuff.animate({ height: "show" }, 700, "easeInQuad");
          } else {
            $infostuff.animate({ height: "hide" }, 700, "easeOutQuad");
          }
          return false;
        }
     );

    Hope that helps.

  18. Scott

    Thanks Karl. Unfortunately, the click function and test for visibility results in the same behavior. As Dave posted, it seems that Firefox immediately processes the document ready statement a second time, triggering the hide() statement again and closing the content immediately upon expanding it. I believe I could get around it by adding display none; to the css file. However, with javascript disabled there's no way to see that content. So I'd prefer the hide statement in the js rather than CSS.

    I've solved the issue by having two links, one to open, one to hide in Firefox. Not the most elegant solution, but it works as expected. Luckily It's a php driven site so I can filter for each browser easily with separate includes.

    I'll look into the bug tracking mailing list, thanks for the link.

  19. Hi Scott,

    I must be missing something. I put up a simple test page using the code you printed above, and it works fine for me on Firefox 2.0.0.12 Mac. Please check out the page and let me know if I'm missing the point.

  20. Scott

    Thanks Karl.

    I tried to build a test page to show it as well. This lead me to discover it's a conflict somewhere, not a bug. I haven't been able to track where specifically the conflict exists yet. I'm running jcarousel and shadowbox as well. I'm thinking shadowbox is causing conflicts with jquery in Firefox. I'll be certain to post back when I narrow down the specific conflict.

  21. Rob

    Hi,

    I really like the script. I am working on a long government document and I want to be able to show and hide certain blocks of text.

    Here's the problem that I have. Should someone want to print out the entire document (even the hidden parts), it seems that it cannot be done if this script is being used to show and hide stuff. If I display all the hidden parts, then it works. But what if there are 50 hidden blocks of text? This would mean I would have to display all 50 blocks before printing which the end user might not know they would have to do.

    Is there anyway to write some JS that will turn this show/hide feature off whenever the page is printed.

    Thanks,

    Rob

  22. Hi Rob,

    One option might be to include a print stylesheet that explicitly sets the display property of all those elements to block. you might need to use !important as well. Haven't tried it, but hopefully that leads you in the right direction.

  23. ok, im looking for learn jQuey, this example i thinks is nice, but....dont said nothing about call the js form the buttons....

    im loss

    thanks

  24. Nice one! I am new to jQuery and finding it very frustrating to get my head round - up to now I've only been involved in CSS web design.

  25. Thanks for this, Karl. I really appreciate the work you do. I have a question on the test page that you set up for Scott. I want to do something similar with a sprite-based navigation, but need the toggle to be on the hover event, not the click. How would I do that?

  26. Oh, and another question: how would I make reverse the direction of the animation? Thank you! I think I am going to buy your book. . .

  27. aa

    Hi,

    I really like the script. I am working on a long government document and I want to be able to show and hide certain blocks of text.

    Here's the problem that I have. Should someone want to print out the entire document (even the hidden parts), it seems that it cannot be done if this script is being used to show and hide stuff. If I display all the hidden parts, then it works. But what if there are 50 hidden blocks of text? This would mean I would have to display all 50 blocks before printing which the end user might not know they would have to do.

    Is there anyway to write some JS that will turn this show/hide feature off whenever the page is printed.

    Thanks,

    Rob

    Rob, try the css media print ....

  28. ditax

    How to hide editor/textarea with jquery? thx

  29. Rohit

    nice example thanks

  30. Hi nice article, I have one very easy and short which will work on a button click here is the code

    $(document).ready(function(){ // This Function check for ready position
    $("button").click(function () { //When you press the button if div is visible it will hide it.
    $("div:visible").hide("slow");
    }
    );
    $("button").click(function () { //And if div is hidden it will show it
    $("div:hidden").show("slow");
    }
    );
    }
    );

    In above example your contents will not be shown when ready. To show contains use following line after ready function

    $("div:hidden").show("slow");
    Have some style for div

    div { width:auto; height:auto; margin:5px; border:3px outset green; float:left; }

    Now Create the Button:

    Show hide div

    And at the last use div:

    This is the Test layer for show or hide your page.
    can get download at http://www.jagadishwor.com.np

  31. Nimantha

    Can you please explain how to do it coz im new to this, I want to show and hide some contents on my web page so please tell me from the begging coz I can't understand $(document).ready() function.

    Thank you.
    Nimantha

  32. Hii..can any one tel me how we can use this in wordpress just like what s done here

  33. Mark

    Thanks for the great code. I have a follow-up Q:
    on your acronyms, you have a different style (dashed lines instead of solid). Can you share the details of how you did this? Thanks!

    • Hi Mark,
      You just need to set the border-bottom property for the acronym. Something like this:
      acronym, abbrev { border-bottom: 1px dotted #d44314; }

  34. Galina

    How you show hide on mouseover using jquery, every example is on click. I would like to know how to show log in control on mouseover hyperlink Please login.
    thank oyu

  35. Vinnycius

    Thank you man..

    That was very helpful!!!

  36. Hi.

    Since a last few month i try to learn jquery very fastly in short time but not so possible but after visiting this page , now i can work better on jquery , thanks a lot dear

  37. WeaponsTheyFear

    I am having trouble with hiding in created elements. I click on a title, and it loads a page inside a div. The contetn that was loaded has some css that SHOULD be hidden by default, but is not (content loaded is a form, and things that are hidden are errors messages).

    I ran into similar situation where I needed to use LiveQuery but am at a loss as to why this isn't working. I have been able to find nothing about it.

  38. CS

    I am really new in this.
    I tried the example, but the title part only was hidden for 1 second or 2, re-appeared, which makes me think the hiding is only linked to the click event, and the effect is gone after the click event finishes... Could you please shed some light?
    The jQuery part:

    
    $(document).ready(function() {
        $('#hideTitle').click(function() {
            $('h1').hide();
        });
        $('#showTitle').click(function() {
            $('h1').show();
        });
    });
    
  39. Hi, could you please show how you do that show/hide with submit-buttons?? I dont really get that. I get it to work with a-links but not with submit-butons. I put an id on the submit-button but it doesnt work.

    The reason i want to do that is because i dont want this little sign "#" to appear in the browser URL when you click a button cause if you are far down on the site och you click one of those buttons with an href="#" then you automaticaly (spelling?) go furthes up on the page? But is it a way to get around that? Without using submit-buttons? That would be great thanks:D

  40. JR

    Karl,
    Your posts are very clear and helpful. I'm going through this methodically.

    Where is: "How did I attach the hiding and showing to those buttons? I'll show you that in my next entry."

    Thanks

  41. Ashu Pal

    For Make an element by default hidden when the page loads, the above code should look like this:

    
    $(function() {
                  $("#h1").hide();  // by defining it before click function make it by default hidden.
    	        $("#ToggleButton").click(function() {
    	        $("#h1").toggle("slow"); });
                 });
    
  42. bhomatude

    Trying to learn the basics... Here is a script for three toggle buttons that each when clicked open their corresponding divs. Fine. Now how does one go about automatically closing an open div when clicking on a new 'toggler' that opens it's div? I see other posts about this very question, but I'm just not grasping the logic.

    jQuery(document).ready(function($) {
    $("#toggle1").click(function () {
    $("#toggle1div").toggle("drop", {direction:"right"}, 500);
    });
    $("#toggle2").click(function () {
    $("#toggle2div").toggle("drop", {direction:"right"}, 500);
    });
    $("#toggle3").click(function () {
    $("#toggle3div").toggle("drop", {direction:"right"}, 500);
    });
    });

    I am thinking that I could somehow incorporate this code:

    if ($("#toggle2div").is(':visible')) {
    $("#toggle2div").hide();
    }

    like this:

    jQuery(document).ready(function($) {
    $("#toggle1").click(function () {
    $("#toggle1div").toggle("drop", {direction:"right"}, 500);

    if ($("#toggle2div").is(':visible')) {
    $("#toggle2div").hide();
    };

    if ($("#toggle3div").is(':visible')) {
    $("#toggle3div").hide();
    }

    });

    But that doesn't work... Help?

  43. Cel

    Hi Karl, I'm sorry to bother you with my question, but I've read all the comments in this post and on the next entry regarding this topic and I didn't find the solution. I've also read Working with events part 1 but I'm still having problems.
    I copied your code and the only thing I changed are the id's so they would fit on my css. I'm using the jquery lib 1.4.2 but I'm not using any ohter javascript/jquery plugin that could cause trouble, so my guess is I'm writting something wrong.

    Here's the js part:

    
    $(document).ready(function() {
      $('#shown1').hide();
      $('a#show1').click(function() {
        $('#shown1').show('slow');
        return false;
      });
      $('a#hide1').click(function() {
        $('#shown1').hide('fast');
        return false;
      });
    });
    

    and here's the html for it:

    
     < a href="#" id="show1" > More < /a >
     < div id="shown1" > < a href="#" id="hide1" > Close < /a > < /div >
    

    This is a great site, I've added it to my favourites. Thanks for your time, Karl.

    • PAW

      Hi Cel!
      I think it is you selector that are wrong try to remove the a letter before the # so you only use the id as the selector 'a#hide1' should be '#hide1'

  44. martin

    i need some help... i'm in the process of testing a site, http://joryadamson.com, that uses the show/hide code. it's all working perfectly in firefox, safari, opera, chrome and ie8 and 9. i even added a bit of extra scripting so that, as well as the toggle button, the pop up div closes when the user clicks anywhere away from it.

    instead of doing what it's supposed to in internet explorer 6 and 7, the pop up divs disappear when they're clicked on and the #sign_in_popup div toggles visible.

    forgive the messy layout in these 2 browsers as i'm still wrestling with the way ie6 and 7 are interpreting my css!

    i'm not much of a jquery or javascript fiend so forgive me if fixing this amounts to childs play, but i'm stuck and getting more and more frustrated with it. any pointers/fixes would be very welcome indeed. thanks!

  45. Sman

    I would like the show and hide be dependent on if there's content being shown within a div tag (e.g. div#related). This would affect a header, like <h4>My Header</h4>. So if div#related doesn't contain any content, hide <h4>My Header</h4>. If it does contain content, show the header.

  46. STOPBIT

    I just need the toggle function and to hide when the page loads, so updated the hide show js to this :

    // basic toggle  - hiddeen when page loads
     $(document).ready(function() {
       $('#toggle').click( function() {
        $('div.showhide').toggle();
       });
          $('#toggle').ready( function() {
        $('div.showhide').toggle();
       });
    });

    I then simply used this code to display on the html page and of course matched the id name to "toggle". This means my h1 does not get hidden when the button is clicked only the class in the div :

    Table line 1
    Table line 2
    Table line 3

    Hope this helps someone. It's so simply you could shake a stick at it.

3 Pings

  1. [...] We've received a number of comments recently from people looking for variations on the showing and hiding theme. For the basics, you can take a look at two earlier entries, Basic Show and Hide and Slicker Show and Hide. [...]

  2. [...] Doe dat met jQuery. Nu zit je met tagsoep (onclick bij een link). Is niet de beste manier van werken. Basic Show and Hide Learning jQuery - Tips, Techniques, Tutorials [...]

Sorry, but comments for this entry are now closed.