Slicker Show and Hide

read 297 comments

Last time I showed you how to make something appear and disappear on a web page. This time I'll show you how to do it with style.

Like we did last time, we'll start with our $(document).ready() and put everything else inside of it.

Adjust the Speed

This time, however, we're going to adjust the speed at which our item shows and hides. To do so, we put a speed indicator — "slow" or "normal" or "fast" or a number of milliseconds (1000 = 1 second) — inside the parentheses:

Continue Reading Below
  1. $('#slickbox').show('slow');

Note: If you use a speed word, put it inside quotation marks (either single or double); if you use a number, omit the quotation marks: $('#slickbox').show(500);

Attach Effects to Events

The final step here is to attach the effects to events. Last time we attached our effects to the "onclick" event of buttons. This time we'll attach them to links. But here's the rub: Links already have events attached to them. They take the user to whatever URL is indicated in the "href" attribute, usually another page. That means that we not only need to make something happen, but we also need to stop the default thing from happening. We can prevent the default behavior by adding return false;.

So let's take a look at how we would tie the "onclick" event of one link with an ID of "slick-show" to the "show" effect. Here, show() will display a DIV with an ID of "slickbox":

  1. // shows the slickbox DIV on clicking the link with an ID of "slick-show"
  2.   $('#slick-show').click(function() {
  3.     $('#slickbox').show('slow');
  4.     return false;
  5.   });

Notice that we attach ".click()" to "#slick-show". In jQuery, events will often have anonymous, or lambda, functions inside them. That's why inside the parentheses of ".click()" you see function() { ... }. By the way, it's called an anonymous function because it has no name associated with it. I don't know why it's also called a lambda function. Can someone enlighten me?

Here is the final code for three effects — show(), hide(), and toggle(). I've added $('#slidebox').hide() as the first line after $(document).ready() to hide that DIV when the page loads.

  1. $(document).ready(function() {
  2.  // hides the slickbox as soon as the DOM is ready
  3.   $('#slickbox').hide();
  4.  // shows the slickbox on clicking the noted link  
  5.   $('#slick-show').click(function() {
  6.     $('#slickbox').show('slow');
  7.     return false;
  8.   });
  9.  // hides the slickbox on clicking the noted link  
  10.   $('#slick-hide').click(function() {
  11.     $('#slickbox').hide('fast');
  12.     return false;
  13.   });
  15.  // toggles the slickbox on clicking the noted link  
  16.   $('#slick-toggle').click(function() {
  17.     $('#slickbox').toggle(400);
  18.     return false;
  19.   });
  20. });

Look closely at the code and you'll see that our slickbox will show at a slow speed, hide at a fast speed, and toggle somewhere in between (in 400 milliseconds).

Demo 1

Try it out for yourself. Just click on the three following links:

Show the box  Hide the box  Toggle the box

This is the box that will be shown and hidden and toggled at your whim. :)

Newbie Tip

For those of you brand new to JavaScript as well as jQuery, the lines of code that begin with two slashes ( // ) are comment lines that have no effect on the code whatsoever. You can also create multi-line comments by enclosing them in /* and */

Other Effects

Other simple jQuery effects for showing or hiding elements include:

  • slideUp()
  • slideDown()
  • slideToggle()
  • fadeIn()
  • fadeOut()

Demo 2

Try the slide effects to see how they differ from show/hide:

Slide the box down  Slide the box up  Slide toggle the box


For more sophisticated effects, check out Stefan Petre's Interface plugin jQuery UI


If this type of showing and hiding isn't exactly what you're looking for, please check out my other entries and the jQuery UI Accordion:

comment feed


  1. jquery fan

    What bout when you have 10 items you want to hide show, fadin fadeout. Then how do you get the open one closed before the new one opens?

  2. Ah, that's a good question. It depends on how you have the items set up, but one thing you should definitely look at is the long list of selector expressions such as ":visible" and ":hidden" and ":next" You can find them here. Also, I think I'll write a new entry sometime in the next week or so that explores the topic a little more fully.

    Thanks for the comment!

  3. Justin

    is it possible to tpggle/slide/etc. all elements with the id of slickbox

    i have 10 table row each with the id of slickbox

    when i use the example above only the first row toggles.etc..

    Is there a way to toggle all with the one click?


    [email protected]

  4. Hi Justin, I noticed that your question was answered in the jQuery discussion list, but just in case somebody else comes here with the same question, the answer is that an ID should be used only once per page, while the class attribute can be used many times.

    If you change <tr id="slickbox"> to <tr class="slickbox">, that should do the trick.

  5. piotr

    This looks great. I already used it for my website but there is one thing that I miss in this script - Cookies. After the content slides in I want it to stay there after I refresh the website.

    Is it possible to add cookies here?

    I will be glad to get some help from you. Thanks.

  6. Hi piotr,

    Klaus Hartl put together a cookie plugin for jQuery that should do the trick. If you want to roll your own, take a look at Peter-Paul Koch's quirksmode article.

  7. Don

    Hello All,
    I just found JQuery and I am trying to get this example to work for me. I have created a basic html page and .js file but I am unable to get anything working. Any help on this would be great!

    .hideus {height: 100px; width:100px;}
    <script src="/scripts/jquery.js" type="text/javascript"></script>
    <script src="/scripts/links.js" type="text/javascript"></script>
    <div id="main">
    <a href="#" id="HomeLink">Test to see if this works</a>
      <div id="testhide" class="hideus">
      This should be seen first.....
      <div id="HomeDiv" class="hideus">
      This will show up once I press the link

    here is my link.js file:

    $(document).ready(function() {
     $('a#HomeLink').click(function() {
        return false;

    Also, what I would like to have happen is at the opening of the page all of the "hideus" classes should be hidden and then a specific division should then fade into view. Can I add more that one function the the Document.ready?

    Thank you,

  8. Hi Don,
    There are two problems with your code. The first is that you're referring to #hideus, which is interpreted as an element with an ID of "hideus." You need to refer to .hideus instead, just like you do for the CSS.

    The second problem is that the click event needs to go inside $(document).ready() as well. Try this instead, and let me know if it works:

    $(document).ready(function() {
      $('a#HomeLink').click(function() {
        return false;
  9. Don

    That's got it! Thanks for your help.


  10. Albert

    Hello i'm very new to jquery.

    How is the slidedown-toggle effect achieved?

  11. Albert

    Nevermind, i think i'm becoming blind :)

  12. Jim

    Similar to the first post - I have a dynamic list I'm generating using ColdFusion and I'd like to be able to add a show/hide toggle to each list item but can't figure out how to get the unique ID for each row item to jquery...

    <a href="##" class="slick-toggle-#currentRow#">Details</a>

  13. Dion

    Dear Karl,

    Is there any way to use slide-toggle with a different hide and show speed? In the above example you set one speed to toggle and different speeds for hide and show.

    Thanks for reading and for the tutorials.

  14. Dion, if you use .slideToggle() or .toggle(), the one speed that you set will be applied to both the showing and the hiding. So, to get the show speed to be different from the hide speed, you'll have to use .show() and .hide() — or .slideDown() and .slideUp() or whatever — separately.

    I hope I understood your question correctly and answered it clearly. If not, let me know.

  15. I'm relatively new to jQuery, but with the help of various tutorials I have what I want to do working. My question is more on "how best to" accomplish this. Basically, using the slideToggle() I want to have multiple divs that can be expanded or contracted to show addt'l info if needed.

    The way I'm doing it now is running a loop around 3 parts of my code - the CSS, the javascript and the display code:

    <cfloop from="1" to="3" index="i">
    ##slickbox_#i# {
    width: 510px;
    background: ##eee;
    border: 1px solid ##900;
    padding: 10px 5px 10px 5px;

    and then in my javascript:

    <cfloop from="1" to="3" index="i">
    $('a##slick_#i#-slidetoggle').click(function() {
    return false;

    and in the display code (you get the idea).

    Is this the best way to have jquery perform the same effect on multiple divs independently?

  16. I am trying to do something clever, but fear I am under qualified. As well as posting here, I am working through 2 ajax books and a javascript book. Here is the goal:
    A form. Three items in the drop down menu, A,B and C. If you select A, there appears a text box with a label. If you select B you get a text area, again with title, select C to see another drop down menu.

    By using the wonderful online manuals here (thank yuo!) I have managed to do a rough hash of this, but as well as selecting from the dropdown, you have to click a link or button to show the relevant area.

    So any ideas how I can acomplish what I want? It may be that there is a perfect tutorial or example that I have missed - I have been working all day on this with Google etc, so if you know of a tutorial that will educate me so I can do this that would be awesome! It may be that I am searching with incorrect phrases (learning the lingo still!)

    Thank you in advance for any assistance you can offer.

  17. Hi John,

    If your "drop down menu" is a <select> element, you can use the .change() method to trigger the loading (or showing) of the other element.

    Here is a very rudimentary example for a <select> element that has 3 options with values of "1," "2," and "3":

    $('select').change(function() {
      var thisValue = $(this).val();
      switch (thisValue) {
        case "1":
          //code for inserting or showing text field with label goes here;
        case "2":
          //code for inserting or showing textarea goes here;
        case "3":
          //code for inserting or showing drop-down menu goes here;

    Hope that helps.

  18. Joao Nobre

    Thanks for the tutorial and for the very good work with jquery.

    I have a question:

    I want to have the show/hide effect, but overlapping the existing elements, not "elastic". This is to use with a navigation menu.

    How could I achieve this?

    Thanks again for your effort and for your attention.

  19. Hi Joao,
    I'm glad you like the tutorial and appreciate the encouragement. I think the easiest way to achieve the effect that you're attempting is to set a CSS declaration of position:absolute in your style sheet for the element to be shown and hidden and set its containing element to position:relative.

  20. Benn

    Love the code and the demos ,but It kind of seems to be to much code for 2 functions that I need.
    I need to slide one div down ,and kind of excelerate the slide at the end ,so the efect will look like hard drop(I hope you understand).And slide the cond div from left to right . Now 59kb of jquery looks to be to much for this.

    Should I use diferent script to achive this efect? And if so, could someone please help me with the demo or including the code in the head. My comment is geting to long sorry but I have to say this ,last few days I am reading about moo tools and all the mo shmo and wikki and scriptaculus miraculus and so on but for a beginer none of this super light scripts have the actual demo site like here.

    I also went to your buddy's Stefan Petre's site .His code is awesome and the demos show what I need but his files are much bigger that jquery itself
    So please any one, try to help

    Best regards

    Thank you

  21. You guys are completely crazed.
    I can not believe you have wrapped up JS into something seeminly very useful.

    Your work is in keeping with some of my inventions/creations.

    I hope to contribute later in the year....

    Super Job!!

  22. @Benn,
    Glad you're enjoying the demos. I'm not sure where you came up with the 59kb size for jquery.js. The compressed version is right around 20kb, which IMO, is still pretty lightweight. To get your accelerated effect for the slide down, you can use one of the easing plugins: Easing (3.2kb un-compressed) by George Smith or the easing component (2.6kb un-compressed) of the Interface plugin suite.

    Thanks for the kudos. However, I can't take any credit for jQuery itself. That belongs to John Resig and the development team. I'm very proud to be a part of the jQuery project team, but my role is limited to spreading the word and providing tutorials and general help to those who need it. I'm looking forward to seeing your contributions! If you haven't done so yet, you should check out the jQuery discussion list (now a Google Group).


  23. Aaron

    How would i have multiple links that would show or hide a div or append content to a div from the title or caption?
    This code is great and almost what i am looking for.
    I want to have images that when you mouse over it fades in a div on the right side of it and when mouse over the next one it fades out the previous and fades in the next div or have it append some content from the title tag from the link.
    I have tried modifying this code but am having no luck.
    Here is example HTML of the layout.

    <table width="100%" border="0" cellspacing="0" cellpadding="0" id="ImageTable">
    <td class="images">
    <A href="#"><IMG src="Image.jpg" border="0"></A>
    <A href="#"><IMG src="Image.jpg" border="0"></A>
    <A href="#"><IMG src="Image.jpg" border="0"></A>
    <td class="divs">
    <div>1 This is the box that will be shown and hidden and toggled at your whim.</div>
    <div>2 This is the box that will be shown and hidden and toggled at your whim.</div>
    <div>3 This is the box that will be shown and hidden and toggled at your whim.</div>

    I am so lost on how to get this to do this and can not tell you how much i would appreciate it if someone could help me out.
    Thanks again for everything and great work!!!

  24. Hi Aaron,

    I just put a little test page up. Take a look and see if that is what you're looking for. The code is in the head

  25. qt

    Hi there

    Sorry, inserted this post on the wrong page. Now here again...

    Thanks for the good ideas!
    I just wonder, how I can pass a variable with a Link that toggles a div-container that contains a form.

    Let's say I have a list of items and I want to offer a form to edit the records, how can I pass e.f. the id of a record to the form in the toggable div?

    It does not work with just
    <a href="#?id=2" id="togglediv">My entry</a>

    Any hints on this?

    Thanks a lot for any info!

    Cheers, QT

  26. Hi qt,

    I'm not sure exactly what you're trying to do here. Are you trying to pass "2" to a field in the form or to the action attribute of the form? Do you have a demo page up somewhere that shows/explains what you're trying to do? Or maybe are you trying to make a request to the server for information (from, say, a database) that will populate the form for you? If it's the latter, you might want to look into the $.post() or $.ajax() method.

  27. qt

    Hi Karl

    Thanks for your reply.

    Yes, it's your last assumption:
    I want to get data from an existing record from the database.
    I checked on the $.ajax()-method but did not get a running solution, yet.

    In plain PHP the call would be something like this:
    <a href="det_record?id=2">edit record&lt/a>

    If you have an example and can lead me to a solution, that would be awesome!

    Thanks again!

  28. qt

    Hi Karl

    never mind, I figured it out.

    But thanks for all the good examples!

    I may post my solution here, as soon as I'm finished.
    If that's ok with you.

    So long!

  29. Hey, sorry I wasn't able to get back to you on this, but I'm really glad you figured it out. Feel free to post your solution; it could prove helpful to others trying to do the same thing.

  30. Crimson

    I had used usableforms.js to show and hide parts of my form but the one disadvantage is that it uses a custom attribute "rel" and hence does not validate properly. I am new to jquery and was wondering if someone would help to mimic the usableforms with jquery.

    Thanks in advance for the help!

  31. I wish qt had posted his fix, because I'm having a similar issue, I think.

    The script is working beautifully. I have the toggle link position:absolute;'ed right at the top of my page; however, after clicking the link I'd like the window to move down (since there is some stuff before the expanded div, ie,

    <a href="#content" title="Show content">Show content</a>
    doesn't jump down to #content. How can I get this script to scroll down to the expanded area?

  32. MarmieRawda

    i've been trying to get this slide-down code to work for my site but i seem to go nowhere. im using joomla n have placed these in the head section of the php:

    the rest of the script:

    Show the box  Hide the box  Toggle the box
    This is the box that will be shown and hidden and toggled at your whim. It has inline styles, which typically is a bad thing, but for the sake of our demonstration, we'll let it slide, right?

    i'v placed in a table in the body section just to see if it works but it doesn't.
    am i missing something here?
    iv got the js files in my server, correctly named, no typo whatsoever.


  33. MarmieRawda

    sorry bout the earlier submission

    i've been trying to get this slide-down code to work for my site but i seem to go nowhere. im using joomla n have placed these in the head section of the php:

    <script src="/scripts/jquery-latest.js" type="text/javascript"></script>
    <script src="/scripts/slide.js" type="text/javascript"></script>

    the rest of the script:

    <a href="#" id="slick-show">Show the box</a>  <a href="#" id="slick-hide">Hide the box</a>  <a href="#" id="slick-toggle">Toggle the box</a></p>
    <div id="slickbox" style="background: black; height: 135px;"><p>This is the box that will be shown and hidden and toggled at your whim. It has inline styles, which typically is a bad thing, but for the sake of our demonstration, we'll let it slide, right?</div>

    i'v placed in a table in the body section just to see if it works but it doesn't.
    am i missing something here?
    iv got the js files in my server, correctly named, no typo whatsoever.


  34. Hi MarmieRawda,

    Can you post a link to the page that you're working on? I would need to see exactly what's going on in slide.js and also see the context of your HTML to be able to help.

  35. MarmieRawda

    hi Karl,
    i managed to get the script to work now. was my bad overlooked the directory the files were in. but now my problem is the content in the slide box. i've placed a shockwave flash in it. it disappears but only does so after the box has completed sliding up. is there a way i can work around this so that it appears as the content of the box is also sliding up instead of disappearing so suddenly at the end?

  36. Hmmm. I'm not sure about the shockwave flash object. Those things are notoriously tricky because they aren't technically part of the page itself. I have very little experience working with them, so I'm afraid I can't be of much help. Is there some parameter that can take "transparent" as a value? That might help. I suggest you post the question on the jQuery discussion list and see if someone there can help out.

  37. MarmieRawda

    thanks Karl for your help and for the script. the team has decided to change the whole look of the website tho but thanks again!

  38. Nice tutorial.. works smoothly..

  39. dan

    I'm using the slidetoggle effect to show/hide a comment box on a page with 5 or 6 different news stories on it.
    I've got it working using only one story's comment box, however i'm not sure how to accomplish this without having all the boxes being toggled at once.
    Each story has an id so I could append the story id to the "#slick-toggle" link so it would be #slick-toggle-24829 or something along those lines, but i'm still not 100% sure on how to achieve this.

  40. Hi Dan, you should be able to accomplish this by using the this keyword to set the context and using classes instead of IDs. I can't give you the specific DOM traversal without seeing your HTML, but if you look at the Accordion Madness entry, that does pretty much the same thing you're trying to achieve.

  41. dan

    Hi, if you don't mind I would appreciate further help on this.

    Here is the layout with the toggle link and the comment box

    <div class="story">
                <div class="storytitle">hello</div>
                <div class="storybg">blah blah blah</div>
                <div class="storybottom"><a href="#" id="comment-toggle">comment</a></div>
                <div id="commentbox" class="details" style="display:none;">add comment</div>

    And the jQuery code i'm using, which I took the majority of from your example:

    $(document).ready(function() {
      $('a#comment-toggle').click(function() {
    	return false;
  42. Aureole

    I can't get it working... =( I have this in the <head>

    <script type="text/javascript" >
    $(document).ready(function() {
      $('a#showsubmit').click( function()
        return false;
      $('a#showmanage').click( function()
        return false;
      $('a#showarchive').click( function()
        return false;
      $('a#showfeed').click( function()
        return false;

    Then for my HTML I have

    <a href="#" id="showsubmit" title="Submit News"><img src="..." /></a>
    <a href="#" id="showmanage" title="Manage News"><img src="..." /></a>
    <a href="#" id="showarchive" title="News Archive"><img src="..." /></a>
    <a href="#" id="showfeed" title="News Feed"><img src="..." /></a>
    <div id="hiddensubmit">
      <p class="newsinfo">Stuff here....</p>
    <div id="hiddenmanage">
      <p class="newsinfo">And some more stuff...</p>
    <div id="hiddenarchive">
      <p class="newsinfo">Stuff goes here too..</p>
    <div id="hiddenfeed">
      <p class="newsinfo">And here....</p>
  43. neoman

    Hi guys, I have a bit of a problem here.

    I'm using .hide() and .toggle() in my script, for hiding the login/register from which is on the top of the page. And everytime I open a page with a lot of content on it, there is a "bump" on my page. The register form shows for a brief moment and then the whole page jumps back up and hides the form like it should. Can this be bypassed?

    My page:

    Thank you in advance.

  44. Aureole, can you describe what, if anything, is happening when you click on one of the links?

    Neoman, nothing occurs to me at first sight. I can't be sure, but it may have something to do with the way Joomla is loading the script reference. When I go to the "Gallery" page, the Login/Register form is never hidden. This would be a good question for the jQuery Google Group. I know there are a bunch of Joomla people there who might have a better idea what's going on.

  45. Philip Ridout

    i wanna create a div that slides down as a one pixel line (or maybe more, depending on how it looks) and then slides out to the right. is this possible using jQuery?

  46. Hi Philip,
    Not sure what you mean by "slides down as a one pixel line." One pixel width? Would the line start "hidden" and then grow downwards, followed by its contents being gradually revealed horizontally?

  47. Hi - Thanks for providing this example. This is just what I would like to do. Unfortunately, I think I must be missing a key concept because I just can't get it to work. Here's a sample page I am working on: I would like to toggle the page numbers and have the book excerpts underneath slide open and closed, just as in your example. I tried to copy your code and html but something isn't quite right. I would appreciate any help you could give. - Karen

  48. Hi Karen,
    It looks like you need to adjust the path of your jquery.js include by preceding the path with a slash ( / ). So, instead of this:
    <script type="text/javascript" src="jquery/jquery-"></script>

    it should be this:
    <script type="text/javascript" src="/jquery/jquery-"></script>

  49. Oh. Duh.
    Thanks, it works fine now.
    Here's another question: why do I need that entire jquery file if I am putting my own script at the top of the page? Obviously there are things in that file that I need to make the sliding toggle script work, right? Is it a master file and I am just using some pieces of it for this particular effect? And the stuff in the master file is kind of like my CSS file? Where I have all my styles in one document but I could also have an inline style here or there in my document as needed? Just trying to get a handle on the overall concept of jquery. I've read through the documentation but it's not really written in a "for Dummies" format. Thanks for your help. -K

  50. Luis

    Hello, and congratulations on this interesting reading.
    I was trying to make a table slideUp when a link on a table is clicked. On IE7 the slideUp doesn't slide at all, it just disappears... If I place the table within a div, and slide the div it all works ok.
    I was trying not have extra markup, nor unnecessarily adding a div wrapper in code to allow this to work...
    I'll leave a sample of the code to be applied to a simple table, with 30 or so rows, with different text sizes on the cells, and with a link in a cell on each row.

    Can anyone comment on this please.
    Also, If I try to hide every row but the one clicked, when latter I try to show all the rows again they show up, but in a very ugly presentation...

    $(document).ready(function (){

    Thanks in advance

  51. Milan

    'Lambda function' comes from Lisp and the lambda calculus. Ask wikipedia for the details.

    • Suncat2000

      you may have misunderstood the term "lambda function", confusing it with an anonymous function.

      In Microsoft's C# language, you can create an inline delegate function with a special syntax "args => expression". This is called a lambda function. It is similar to an anonymous function, being that neither have names, but it isn't the same. Lambdas have other properties that make them useful for other purposes in .NET.

  52. Great job on this great tutorial.

    One possible bug I've found though, which maybe you can consider for future revisions, or suggest a solution for me.

    If I use the slide toggle on a page called "index.html" on say ten divs containing text, with trigger elements something like Click here for details, followed by the hidden div.

    When I link from another page to say...


    It takes me to a blank space way down the index.html page, where #test5 would be if all the slides were shown.

    Is it possible to create a remote link to a trigger element, that also displayed the div? So clicking
    /index.html/#test5 would take you to the index.html page, scroll down to the #test5 id and slide open the next div.

    Thanks in advance.

  53. Zeno

    How about this demo page:



    $("dt a").click(function(){
    return false;

    He used dl, dd & dt to format the HTML code.

  54. Mark Blethen

    I have an IE issue I'm not sure if anyone else is noticing. (I'm using IE7, haven't been able to test anything below it.) When the page loads, the text shows until the entire page is loaded (graphics and all) and then the text will hide.

    For testing purposes, I have created a basic page that looks like this:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    <html xmlns="">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    <script type="text/javascript" src="js/jquery.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
     // hides the slickbox as soon as the DOM is ready
     // (a little sooner than page load)
     // shows the slickbox on clicking the noted link
      $('a#slick-show').click(function() {
    	return false;
     // hides the slickbox on clicking the noted link
      $('a#slick-hide').click(function() {
    	return false;
     // toggles the slickbox on clicking the noted link
      $('a#slick-toggle').click(function() {
    	return false;
    <a href="#" id="slick-toggle">Click</a>
                <div id="slickbox">
                	<p>Toggle this text</p>

    I don't understand why the script seems to be loading after everything else for IE7. I also don't understand why no one else experiences this, as I've seen it on multiple machines running IE7 on examples from other people in the comment section. If anyone knows of a fix, I'd love to hear it.

  55. Victor


    Just to let you know that your demos on this page don't work any more (because of 1.2.1?)
    Firebug console says that there is en error in jquery-1.2.1.min.js file on line 20 ( has no properties)

    Hope this helps - keep up your excellent work!

  56. Victor,

    Thanks so much for alerting me to the problem with the demos on this page! The problem was in my script to animate the scrolling for same-page links. I had to add another condition so that it wouldn't try to animate scrolling for links that look like this: <a href="#">. While I was at it, I added one more check so that it won't try to animate to a named anchor when one doesn't exist.

    The demos should be working here now. Thanks again for your help!

  57. Victor

    You are welcome - thanks for a quick fix.

    Actually, I have a question about 'link scrolling'. Would it be possible to scroll and open hidden element from a link on another page (<a href="page.htm#xyz">)?

    In other words, how can I make visible my hidden element (with an id="xyz") when it matches part of the current page pathname - (.../page.htm#xyz)?

    I guess it should be something along the lines of "animated-scrolling-for-same-page-links" technique?

    Thank you.

  58. I have a search results page that I am trying to jqueryize. Under each result I have a div section that allows the user to email the search result. Right now every result's email box is in class form_email and hence when I click the link in class toggle_email ALL off the div's toggle. How can I localize the toggle to just the form_email inside the current results div? Any advice?


    $(document).ready(function() {

    $('a.toggle_email',this).click(function() {
    return false;


  59. Hi Andy,
    Assuming that "a.toggle_email" and ".form_email" are inside the same div, and not knowing exactly where the two elements are in relation to each other, you could try something like this instead of your click handler:

    $('a.toggle_email').click(function() {
      return false;
  60. Awesome! That did the trick thanks!

  61. Poxline

    I like jQuery !
    and so Thanks Thanks and Thanks for this learning guy !

  62. brwalias


    JQuery has been awesome and I hope to learn it better as I go. I currently have a list element that shows a hidden div when clicked. now how can i make the hidden div that appeared on after the list element was clicked to disappear when I select another list element?

    my code:

    // basic show and hide
    $(document).ready(function() {

    // hides the slickbox as soon as the DOM is ready
    // (a little sooner than page load)

    // toggles the box on clicking the noted link
    $('a#toggleAdminNav').click(function() {
    return false;


    some link
    some link

    some content

  63. Nim

    Hi there,

    Great stuff, just one do I load dynamic (external) content, say something.html into the displayed DIV?

    Any help greatly appreciated.

    Many thanks,

  64. I'm having some trouble with the following code. The idea is to change some text to reflect the current state of the toggled element--a table with an id of "nutrition" and a class of "chart". I have tried to select this table for the if statement in every combination of element type, classname, and id that I could think of. None of them worked. Specifically, none of them worked for the toggled state. According to what I could see in Firebug, the table is toggled between "display:table" and "display:hidden" and it is referred to as "element" the actual line from Firebug is something like " display:table" There are three tables being toggled on the page, so I want to specify only the table associated with the clicked element.


    $("#nutritionBar").click(function () {
    $("#nutritionBar a").text("Expand Nutrition Planner");
    $("#nutritionBar a").text("Collapse Nutrition Planner");


  65. Hi B-Love,
    If you want to bind the click handler to three tables, you should probably use a class name instead of an id for both "nutritionBar" and "nutrition". Also, to get the toggle to affect only the corresponding table, you'll have to use $(this) in combination with traversal methods to target just the single table (since I don't know how your HTML is structured, I can't be any more specific than that). Finally, while Firefox reports display as "table," I believe IE will report it as "block." You might want to try something like this instead (replacing my "placeholder" names with whatever is in your markup):

    $('.someClass').click(function() {
      var $thisLink = $(this).find('a');
      var $toggleTable = $(this).parent().next('table')
      if ( $':visible') ) {
        $thisLink.text('Expand Nutrition Planner');
      } else {
        $thisLink.text('Collapse Nutrition Planner');
      return false; // < -- this might be necessary if someone clicks on the link inside #nutritionBar

    Again, you'll have to change some things, such as the DOM traversal methods and ".someClass", to match your markup, but this should point you in the right directions.

  66. One more thing, make sure that all of the above code is wrapped inside a "document ready":

    $(document).ready(function() {
      // code from comment #66 goes here.
  67. Thanks, Karl! That should give me something to work with. I left out the "ready" as I wondered if it would cause confusion...

  68. I have a bit of a problem with the $(document).ready part. Namely, I have a block that should be toggled with a button, but start out hidden. However, when the site loads, the block stays visible for several seconds before the document.ready code is executed, which doesn't look very clean.

    Do you have any advice how I can ensure the block is invisible throughout the page-rendering process?


    Another problem I've experienced in Firefox: The sliding is very smooth if the computer isn't running a lot of applications, but only after the second toggle. That is, when I first show the block, the sliding is skipped and the block blinks into existence. When I hide it again (and on any subsequent toggles), the block toggles smoothly. Could this be solved with some kind of pre-loading process?

  69. Arancaytar,

    What you're describing doesn't typically happen with document ready. In fact, the whole point of that method is to be able to invoke your scripts after the DOM has fully loaded, but before images and other content completes. I guess I'd have to take a look at your page to see what else is going on to be able to help you. It does matter to some extent what order your scripts are loaded. There might also be an issue when also using a load event in the body tag. One thing you can try, though it's not technically "unobtrusive," is to put your <script> tag at the end of the document, just before </body>, and then pull the block-hiding bit out of the document ready so that it executes right there.

    The problem with Firefox is reminiscent of an issue with an older version of jQuery that occurred only in Firefox for the Mac. Which version of jQuery are you using?

  70. Zach

    I'm on a diet and don't feel like talking about cookies but I must.

    There was just a bit of commenting on it back in December and a link to Klaus Hartl's cookie plugin in response to query wondering if it is possible to remember the state of a toggled box.

    Being the total n00b I am, I haven't wrapped my mind around using the plugin for this purpose. While it would be great if someone would hold my little, well, enormous, hand, but I would just as much appreciate being linked to a page where someone is doing it or a tip.

    All the best!

  71. Micheal

    Hello i read the preveious 71 comment but could not figure out what is the easiest way to make a multiple slide down menu. any working codes around ? I dont want to make multiple functions for each menu. there must be something that make it switches in areas

  72. Susan

    I love jQuery but unless I can find specific examples I have a hard time. I have a sliding div with a toggle image tab directly below. I would like to figure out how to have two tab images a close & a replay, and show the close or replay tab image depending on whether the slidebar div is slideDown or slideUp.

    $(document).ready(function() { 
            function initSlideboxes() 
      var oneDay = new Date();
      setTimeout(function() {$('#slidebar').slideUp(10);}, 5000); 
    ('#slidebar').slideToggle(); }); 
  73. Moshfiq

    Hi, I am also new to jquery but I am getting familiar with it gradually. I have used your nice show hide stuff but I need something more which is similar need with jquery fan. In a site I have some div for show and hide. Initially one div will be shown and others are hidden. When I click on another div to show then the current div will be hidden and the new div will be shown by sliding. It will be very helpful for me.

    Thanx in advance


  74. Hi Moshfiq,

    In the "Update" at the end of this post, I link to a couple other tutorials that will help you do exactly what you want: "Accordion Madness" and "More Showing, More Hiding."

  75. Hi, I've been using the slick toggle and its been working great. Unfortunately on both in Safari and IE the elements that are supposed to be hidden are showing until you hit refresh. In Firefox its fine. Could you see if I am doing something wrong? Here is the page in question to show/hide info from the "buttons" in the centre.

    Many thanks

  76. Deborah

    Thanks for the examples. I'm curious, how this could be applied to side by side columns, rather than just horizontal content? For example, two content divs that sit next to each other. If a link is clicked on the first column, the first column will collapse, and the second column will move over to take some of the physical space the first column just left open.

    Are there certain guidelines that will allow, or not allow that to happen? For example, I'm assuming the second column of content will need to be relatively positioned. Is that correct?

  77. Lance


    First thank you for the straight forward examples but more your active participation in the comments section.

    Second, is there a short way to have an element show at the mouse position? (aka tooltip but more robust)

  78. Hi Lance,

    Funny you should ask. I wrote a plugin a little while ago, called clueTip, that has all the bells and whistles. I have some more improvements that I haven't rolled into a release yet, but you can check out the project page and the documentation/demo if you're interested.

    jQuery also provides access to normalized event properties, so if you want something simple, you could do something like this:

    // assuming that you have a div with id of "tooltip" and it has 
    // position:absolute; and left: -9000px;  or something like that
    // to keep it hidden from view...
    $('someElement').hover(function(event) {
    	var $tooltip = $('#tooltip'), tWidth = $tooltip.width();
    	$('#tooltip').css({left: event.pageX - tWidth/2, top: event.pageY+15});
    }, function() {
    	$('#tooltip').css({left: '-9000px'});

    That should position the tooltip div a little below the mouse position and centered horizontally on the mouse position on hovering over some element; on mouseout, it should be hidden off-screen. If the tooltip doesn't have a defined width, you might get unexpected results with the horizontal positioning. Also, this should all be wrapped in a $(document).ready()

  79. Lance

    Prefect. Thanks.

    Bit of topic, do you have, or know of, a tutorial that displays an RSS feed in HTML in a tab after the label is clicked? AKA, show the latest blog entries but not until wanted.


  80. Lance

    let me explain a bit more. I would like this in the document when first loaded:

    <div id="tabs">
     <ul class="labels">
      <li id="tabLink1"><a href="/DuhaimeMenu.htm">Resources</a></li>
      <li id="tabLink2"><a href="/Blog.htm">MyBlog</a></li>
     <div class="tab-content"></div>
    jQuery Tabs now nicely create the AJAX for the hrefs but I want to load the feed from the blog so it formated nicely.  I also have a feed for the resources pages so the same method would apply to both.  People without JS would just go to the respective home pages. 
  81. Ellen

    I have searched everywhere, but no luck yet. I love the show/hide/toggle, but so far every example has shown it working on entire elements.

    I want to build my faq so that some of the text of each answer appears and then the rest can be selected for show/hide - just as you see on reading abstracts and news posts. I'm using with the questions in and the responses in - a pretty standard implementation. If want to toggle the entire that is straightforward, but I hate that ... I want to see a tidbit to decide if I want to read more.

    I can do it by including a within my element ( in this case) but this requires that I determine manually where the break needs to occur and to hard code the into the text, which seems counter-productive.

    Is there any easy way to achieve this (i.e., determine a point - based on word/character count, for example - and hide the rest - while showing all of extremely short answers) or should I just bite the bullet and code the s by hand?

    Thank you

  82. Hi Ellen,
    Would you mind posting your comment again? It's important to escape your "less than" and "greater than" symbols so they'll show up correctly. Instead of using < and >, use &lt; and &gt;.


  83. Ellen

    Sorry, Karl, I realized that as soon as I hit the "submit" button! (And then you went offline.)

    I was thinking of using a toggle within a <dl> where the <dt> is the question or heading, and the <dd> contains the answer or details - this is a fairly common implementation for FAQs or Catalogue listings. It could just as easily be a header followed by paragraphs, however.

    It would be a very simple procedure to toggle the entire <dd> (or child paragraph) and insert a link that changes text to "more" and "less", but I think it is nicer to emulate situations that provide a couple of lines of the summary or answer before hiding the remainder- so people can decide if they want to bother opening it at all. This is commonly seen with blog/news listings.

    I can see how easy it would be to make this happen if I manually include an indicator of the portion of text to toggle - such as a <span> tag (which will degrade nicely if there is no javascript enabled) - but that becomes quite tedious if there are many items in the list, and seems to be exactly the kind thing suited to an automated function.

    All examples I have seen have shown/hidden the entire contents of an element. This type of separation (of the text to be toggled) would required mixing content and presentation; even if I were to place it in a separate block element - such as a <p> - I would only be doing it in order to achieve the desired presentation. Further, it would not degrade appropriately and still requires hand coding each element individually.

    So, the question: is there a way, using jquery, to automatically determine a split point, based in something like a word/character count, including a buffer to avoid orphans? Is there some other way to achieve this, such as with php?

    Or, should I just go ahead and manually hard code a <span> into the text/content of the element at the point where I want it begin toggling?


  84. Lance


    Do you have any examples where tabs are populated by RSS feeds?


  85. Ellen


    Sorry about the repeated posts, but after all that detailed explanation , it occurs to me that all I really want to know is if there is a way to select the nth word or nth character, so I can then insert my show/hide code after it?

    In the ideal world, I'd be able to also count the remainder of words in the element (i.e, simple subtraction) to ensure no orphans.

    It is some combination of length() size() and slice(), I just have absolutely no experience with javascript.

    I found a wonderful example of someone doing this using the number of <p> elements in a <div> that is easily adapted, if I can make the selection I want.

    Your selector tutorials tell me how to get to every element I want, but I'm still hoping not to have to include the (otherwise unnecessary) additional element (i.e., <span>) into each block of text manually.

    Thanx again (and please, delete the redundant posts if you like)

  86. Great stuff man, just wondered why there is a page contents box appeared in the top right hand corner, it does not appear to be in my html but firebug picks it up though.

    All the best

  87. @Lance, no examples of such. You might want to take a look at the plugins repository. Klaus Hartl has a Tabs plugin, which is now part of the jQuery UI suite. Mike Alsup has a plugin that parses google feeds.

    @Ellen, thanks for clarifying. I put together a little demo last night, and I'll be spinning it into a blog entry within the next few days. Remind me if you don't see it by a week from today.

    @Kelly, the page contents box is created using jQuery, so it won't show up in the HTML, unless you look at the generated source with something like the Web Developer toolbar extension for Firefox. I wrote about how to create the page contents box last summer.

  88. Any easy way of getting rid of it please, I'm trying out your sliding box and this is enough to learn at my stage!
    thanks for quick response before

  89. Karl,

    I have managed to achieve what I wanted partially, as long as the element contains only text.

    I've asked my bro, one of the first school of programmers before the internet existed, to see if he can find a way to make it work with HTML as well.

    For now, the example and description of the outstanding questions can be found at my test page at if you'd like to take a look how I achieved it.

    I'll look for your post.

    Happy New Year!

  90. Ellen


    Thanks to the brilliant function written by my brother, it is complete now and works beautifully. There is just one problem to be fixed, which I'm sure will be done in no time ... right now if the embedded element begins before the <span> is inserted, the script funcitons only on that element, and not the remainder of the outer element in which it is embedded.

    It is a bit of a best guess, since there is no accounting for word length, but it does have an orphan tester and will work on any element. A Hide All/Show All link could easily be added.

    See it at

    I am going to see what I can do to make it a plug-in and get his function into jQuery.

    Still looking forward to seeing your blog on this.

  91. Karl, I'm using K2 RC3 for WordPress, which already includes jQuery. I want to hide a div (#catfeed) containing a list of category feeds on page load, but toggle visibility when a button (#catfeed-toggle) is clicked. I adapted your example thus:

    		$(document).ready(function() {
    		$('a#catfeed-toggle').click(function() {
    		return false;

    It doesn't work. Firefox says "Error: $ is not a function". What am I overlooking?

  92. Hi Bruce,
    That error usually occurs when a script tries to use the $ function before the core jQuery file has been loaded or when $ is being used for something else. Try replace each mention of $ with jQuery and see if that fixes the problem.

  93. Karl, many thanks, that was it. I did as you suggested and the toggle for category feeds on my home page sidebar now works as it had with Prototype/ scriptaculous. Now to do the same for my site prefs...

  94. Sorry to trouble you again Karl; I said the code in #92 worked when I changed $ to jQuery. Well, that's true, but I've now tested my site using IE7 and noticed a weird display issue. The toggle briefly flashes the right-aligned icons and then they vanish. They display as they should in Firefox, Safari, and even IE6. If this isn't a CSS issue, could IE7 itself have issues with jQuery? The reason I ask is that I also noticed that the search reset button (next to the search box at the top of my sidebar) has a minor cosmetic issue - again only in IE7. The latter is faded with fadeTo('fast', 0.3); and looks pixelated at the edges under IE7.

  95. Alison

    Hey Karl,

    Thanks for your site! I'm completely new to jQuery (just picked it up today) and I'm trying to create a slick toggle effect and I cannot for the life of me figure out what is wrong with my code.

    This is what I have in the head of my document:

    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
    		$('a.more').click(function() {
    			return false;

    And this is what I have in the body:

    <div class="lede">
    	This is the text I want to show when the page loads <a href="#" class="more">show/hide the rest of the article...</a>
    	<div id="longtext">
    		This is the text I want to toggle (slickly)

    The second paragraph is hidden but won't show upon clicking the link. Can you help?

  96. Hi Alison,

    Check out this test page I put together, using your code. It works fine from here. Does it not work for you? I'm wondering if maybe your page is pointing to an incorrect URL for the jquery core file. Just a guess.

  97. How about toggle of the text?

  98. philk

    I have this code in place:

    $(document).ready(function() {
            $(".toggle").click(function() {
                return false;

    and want toogle this HTML code:

    <span class="toggle">Info</span><a href="#">Some link</a>
    <div class="toggle_content">bla</div>

    It seems that next() only works if the element I want follows right after. But the next element after the toggle class is a link.

    How to create a "generic" toggle for all "toggle" spans that toggle the next following ".toggle_content" class element?

  99. Hi philk,

    Try this:

    $(document).ready(function() {
            $(".toggle").click(function() {
                // return false; <-- no need for this since click is on a span.
  100. Bk

    How do I use this 'show' 'hide' for dynamic content ?
    I may have numerous

34 Pings

  1. [...] Slicker Show and Hide » Learning jQuery - Tips, Techniques, Tutorials JavaScript example code to show or hide some content using jQuery. (tags: javascript tutorial example web code) [...]

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

  3. [...] idea began trying to combine the article on jQuery “slicker show and hide” and Apple style slider gallery. From there, other effects are added to the mix and dug into the [...]

  4. 50 Useful New jQuery Techniques and Tutorials - Programming Blog

    [...] Slicker Show and Hide [...]

  5. 50 Useful New jQuery Techniques and Tutorials | Developer’s Toolbox | Smashing Magazine | 51Feeling

    [...] Slicker Show and Hide [...]

  6. 七平米 » 50个有用的jQuery应用技术和指导

    [...] 48.Slicker Show and Hide [...]

  7. 50 Useful New jQuery Techniques and Tutorials « William Rodriguez Portfolio

    [...] Slicker Show and Hide [...]

  8. 50 Useful New jQuery Techniques and Tutorials « Why Limit Media

    [...] Slicker Show and Hide [...]

  9. Advertisers Blog » Blog Archive » 50 Useful New jQuery Techniques and Tutorials

    [...] Slicker Show and Hide [...]

  10. » 50 новых и полезных jQuery-техник и туториалов endo – luxury coding

    [...] Slicker Show and Hide [...]

  11. 50 Useful New jQuery Techniques and Tutorials | Search Engine Optimisation

    [...] Slicker Show and Hide [...]

  12. [...] with a nice little snippet for toggling a div, I have a good collection of plug-ins and bits assembled to create the look and feel I want within [...]

  13. [...] Slicker Show and Hide – Learning jQuery [...]

  14. » Blog Archive » Bookmarks for Feb 6th through Feb 7th

    [...] Slicker Show and Hide » Learning jQuery – Tips, Techniques, Tutorials – Last time I showed you how to make something appear and disappear on a web page. This time I'll show you how to do it with style. [...]

  15. 50 Useful New jQuery Techniques and Tutorials | Top Web Hosts Review Best Web Hosting 2010

    [...] Slicker Show and Hide [...]

  16. [...] used a slick jQuery solution to toggle the visibility of the slider. The slider is shown by default for the home page and [...]

  17. [...] Accordian – nifty accordian/show-and-hide for cascading content [...]

  18. [...] thanks to Karl Swedberg , his idea is brilliant . Written by ignition in: www [...]

  19. [...] 2) Where is says Ember Your Own JavaScript embedded script code (please include <script> tags), add the following (modified from Slicker Show and Hide): [...]


Sorry, but comments for this entry are now closed.