Registration for jQuery Conference 2008 is closed.

Basic Show and Hide

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.

24 Responses to “Basic Show and Hide”

  1. Aunt Ginny Says:

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

  2. sam Says:

    is there a zip file contain of these code ?

  3. Learning jQuery » More Showing, More Hiding Says:

    [...] 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. [...]

  4. Steph Says:

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

  5. tag hag Says:

    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?

  6. Karl Says:

    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.

  7. Joshua Swenson Says:

    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.

  8. Luke Robinson Says:

    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.

  9. Karl Says:

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

  10. Dave Says:

    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?

  11. Karl Says:

    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?

  12. Blogulate Says:

    Great .. direct and simple.. thanks

  13. dickbob Says:

    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?

  14. Karl Says:

    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.

  15. dickbob Says:

    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!

  16. Scott Says:

    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. Scott Says:

    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.

  18. Karl Says:

    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.

  19. Scott Says:

    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.

  20. Karl Says:

    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.

  21. Scott Says:

    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.

  22. Rob Says:

    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

  23. Karl Swedberg Says:

    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.

  24. asinox Says:

    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

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <pre> <em> <i> <li> <ol> <strike> <strong> <ul>

IMPORTANT: If you wish to post code examples, please wrap them in <code> tags. Multi-line code should be wrapped in <pre><code> </code></pre> Also, use &lt; instead of < and &gt; instead of > in the examples themselves. Otherwise, you could lose part of the comment when it's submitted.