Slicker Show and Hide

read 221 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:

JavaScript:
  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":

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

Notice that we attach ".click()" to "a#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.

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

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

Bonus

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

UPDATE

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

221 comments

  1. Hi Bk,

    Looks like your comment might have been cut off. Sounds like you want events to work for content that is added to the DOM after the event handlers are registered. I offer one way to do this in my latest tutorial, Working with Events, part 1. Hope you find it useful.

  2. Bk

    oops..

    Its ok.

    My question was how do we apply this to dynamic content ?
    The 1st and 15th post have raised the same question, any solutions, let me know.

    I am currently looping the script with unique id, is this the only way ?

    Thank you.

  3. Hi Bk, I guess I was confused about your use of the word "dynamic." If you're simply trying to apply the effect to multiple elements, you can add the same class to each of them and then apply the toggle to the class. For example, $('div.toggle').slideToggle(). You can really use any "selector expression" you want to identify the elements to be toggled. Here is another example: $('#contents p').slideToggle(). That will toggle (with a slide effect) all of the paragraphs inside an element with id="contents". To toggle all but the first paragraph inside id="contents", you could modify the selector slightly: $('#contents p:gt(0)').slideToggle().

    So, you see, it really depends on what you're trying to accomplish. But typically it's not necessary to explicitly loop through the elements.

    • Quin

      Hello Karl,

      This is a interesting one to me...

      I would like to have multiple instances of a link classes 'btn-moreInfo' .
      Once the button (link) is clicked it must show or hide a div classed 'moreInfo'.

      The problem I have is that once I click on any of the buttons classed 'btn-moreInfo', all the divs open. It makes sense because they are classes and not IDs, but I would like to target the div closest to the link that triggers the action. Is it possible?

    • Quin

      First of all, thanks for the prompt reply below Karl. I could not respond to your response, so I did it here again.

      I had a look at the page you suggested and I have it working 80% now.

      Due to my mark-up, I´m finding it difficult to get the content to hide once it is displayed.

      Here is my code if you don´t mind having a look:

      
      
      
      

      The list items repeat for more entries..

      My jQuery:

      
      	$('div#video-clips> ul li div.moreInfo').hide();
      	$('div#video-clips a.btn-moreInfo').click(function() {
      		$(this).css('outline', 'solid 1px red').next('div').slideToggle('fast');
      	});
      

      One more thing... how does one toggle the css on the event. I would like to have the outline css property removed on the button once the div collapses (or closes) again?

      Many thanks for your help so far.

      Q.

    • Quin

      sorry...
      I cant get the code to display properly here....

    • Quin

      I´ll try again....

      
      
      <div id="video-clips">
      	<ul>
      		<li>Title of video clip...
      			<!-- More info button -->
      			<a href="#" class="btn-moreInfo">info</a>
      			<!-- Dropdown div for more info -->
      			<div class="moreInfo">
      				<div class="avitar-video"><img src="#" alt="" /></div>
      				<h4>Title describing video clip</h4>
      				<p>Lorem ipsum dolor...</p>
      				<!-- Comment on this... bubble -->
      				<a class="comment" href="#">Comment on this clip</a> </div>
      		</li>
      	</ul>
      </div>
      
      
  4. t|na

    Hi, i'm very new to css, js and jquery.
    I'm trying to do this but couldn't get 2nd,3rd, 4th item in..
    It must be something to do with the ID but just by changing it in the plain text, i have no idea where to change/add in the codes.

    Here's my codes:

    
    
    body{font-family: "Myriad Pro"; font-size:13px;}
    /* -------------------------------------------------------- */
    /* BUTTON													*/
    .button{
    	background:url(img/button.png)  -32px right no-repeat;
    	color:#2F303D;
    	clear:both;
    	display:block;
    	float:left;
    	font-size:15px;
    	font-weight:bold;
    	height:31px;
    	letter-spacing:1px;
    	line-height:31px;
    	width:auto;
    	margin-right:30px;
    	padding-left:100px;
    }
    	a.button {
    		text-decoration:none;
    	}
    	.button span {
    		background:url(img/button.png) left top no-repeat;
    		display:block;
    		height:31px;
    		line-height:31px;
    		padding-left:10px;
    		padding-right:8px;
    		margin-right:20px;
    	}
    /* -------------------------------------------------------- */
    /* MENU														*/
    .v-menu{
    	width:800px;
    	clear:both;
    }
    	ul.v-menu, .v-menu li{
    		padding:0;
    		margin-left:60px;
    		margin-right:60px;
    		padding-bottom:30px;
    		list-style:none;
    	}
    	ul.v-menu{
    		clear:both;
    		margin-top:6px;
    		padding:6px 10px;
    	}
    		.v-menu li a{
    			color:#2F303D;
    			font-weight:regular;
    			letter-spacing:1px;
    			display:block;
    			padding:4px;
    			text-decoration:none;
    		}
    		.v-menu li a:hover{
    			color:#ff7200;
    		}
    
    function showElement(layer){
    	var myLayer = document.getElementById(layer);
    	if(myLayer.style.display=="none"){
    		myLayer.style.display="block";
    		myLayer.backgroundPosition="top";
    	} else {
    		myLayer.style.display="none";
    	}
    }
    
    <!-- Mootools -->
    
    		window.addEvent('domready', function(){
    			//-vertical
    
    			var mySlide = new Fx.Slide('v-menu2');
    			mySlide.hide();
    			$('toggle').addEvent('click', function(e){
    				e = new Event(e);
    				mySlide.toggle();
    				e.stop();
    			});
    
    		}); 
    
    <!-- HTML -->
    
    <a href="#">CLICK HERE</a>
    
    <ul>
    <li>Lorem Ipsum is simply dummy text of the [...] </li>
    </ul>
    

    And if there's any way i could insert bullet into the subcontent?
    Thanks!

  5. t|na,

    I'm not sure I can help you here. It looks like some of your HTML is missing from the comment you posted. And, you're using Mootools, not jQuery.

  6. Matt

    Hi karl,

    Why would the div content display first on page load and then hide after page load is complete?

    I have a page that has 6 sliding panels for navigation, when the page gets refreshed, the panels reveal their content and then close up.

    Any ideas?

  7. There are a number of possible causes for that sort of thing, but without seeing your page I can only guess what's going on in your case.

    One possibility is that you're including Google Analytics or a JavaScript advertising fetcher or some other JavaScript directly in the body of the page. The browser may be waiting until that is fully read, loaded, whatever, before it gets to the jQuery code, which I assume you've diligently inserted into the <head> in an unobtrusive manner.

    You might want to experiment a bit. Put the reference to jquery.js after the stuff you want to hide, but before any other scripts. Then, immediately after the core jQuery file, put your show/hide script. This time, do not put any of your custom scripting inside $(document).ready().

    See if that does the trick. It's not a pretty solution, but if you're loading other scripts within the <body>, it might be the most practical one.

  8. Josh

    Please help me, I can't get it to work!

    I would like a text link to toggle the show and hide of a div. I have a slide.js and a jquery.js file.

    slide.js contains:

    $(document).ready(function() {
      $('#slidebox').hide();
    
      $('a#slidelink').click(function() {
        $('#slidebox').slideToggle('normal');
        return false;
      });
    });
    

    And the html includes:

    <div id="slidebox">Test</div>
    <a href="#" id="slidelink">Show More</a>

    What am I doing wrong? Thanks!

  9. Hi Josh,

    I don't see anything obviously wrong with what you've posted. Do you have a publicly available page I can look at? It's a little hard to troubleshoot without the full picture.

    Are you sure the jquery.js and slide.js files are loading properly? Is jquery.js being loaded before slide.js?

  10. Josh

    Karl, you are a life saver! I can't believe it was the simplest little mistake! Thanks so much!

    If only there was a webpage debugger!

  11. Josh, have you ever used Firebug for Firefox? If not, you should download it and start using it right away. It will save you countless hours.

  12. Josh

    Thanks for all the help! You can view the page I have made using this script here. Its exactly what I wanted.

    Just one little tweak I would make if I knew how, is it possible to have the page scroll down at the same rate as the div is sliding down? So the user's window is still showing the show more/less link after the transition has finished?

    Once again, many thanks for the help!

  13. Great and excellent article it’s realy helpful. Thanks again.

  14. Great tips and very easy to follow :)

  15. Jess

    Hi and thank you for your useful examples and all of the help you give people! I have a question similar to another commenter. I have a div that is automatically populated with ten images through Wordpress posts, but I'd like to set it up so that only four images are showing with a "show all" link that will toggle the rest of the div open. However it can only be set up as one div as far as I can figure. It does have a fixed height though so I was wondering if I could set up the slide effect to only show a certain percentage of the div and have the remaining amount hidden to be toggled. Do you think that's possible?

    Thank you!

  16. poosk

    Ok I've basically used over 14hours to find out how the show hide thingy works and haven't got any futher from the start.. this is what I'd need: I have three independent divs that are not siblings or parents (and should be hidden expect the first). First of them is the states list, according to user click it opens a city list for the specific state to another div and the from the city list it finally opens the store list to the third div.

    DIV1 .......... DIV2 ....... DIV3
    state1 ...... -city1 ...... - store1
    state2 --> -city2 --> - store2
    state3 ...... -city3 ...... - store3

    Could anyone point me to the right track? thanks for your help and thanks for the great site.. I think I'll spend a long while here studying..

  17. Where you are using the ID to trigger actions, if you have multiple iterations of them on the same page, you would also need to iterate through the creation of the elements within the $(document).ready(function() {

    });
    block.

    -Brian

  18. I'm working on a redesign for a client. Could you please take a look at this?
    http://www.museumofglass.org/beta2.php
    Everything works, but I'm getting a js error in firebug saying that handlers aren't defined. Not sure if it's a big deal or not but would prefer it to not say 1 error at the bottom of the page if I can prevent it.

  19. Andrew

    hi karl,

    any code u got on how to hide and show my embed object just like the xat boxes??

    thanks a lot!

    Philippines

  20. Hi Karl,
    I have been directed to your site through a forum where I posted a question about conditional formtting in a form with a drop down box. I have been advised that comment 17 of this page may help me out. Basicly I am looking for a way where based on the selection of a drop down list I can display certain text input fields in a form. Unfortunatly using the script doesn't give any result. I started reading from the introduction and put a link in the form's head tags to the .js script. In that file I have copied the exact text as shown in article 17. Then I tried the form but no luck. My drop down code looks like this:

    Banner type
    
    Select banner type
    Spotlight banner
    Category banner
    Home page banner
    Premium page banner:
    

    The form on my page is located at: <a href="http://www.hospitality-industry.com title="form with drop down"

    I don't have any experience with developping and hoped you could have a look and see what I am doing wrong here.

    Cheers,
    Tammo

  21. Nedave

    Hi Karl, I was working on how to create a CSS Dock Menu using the Jquery Javascript library and Fisheye component from Interface at: http://www.ndesign-studio.com/blog/design/css-dock-menu/. I am trying to change the dock menu such that it can be navigated via the keyboard arrow keys (i.e. key codes 37 - 40 using the onkeyPress() method) only and the main menu (at the bottom) could have unlimited sub-menus with a similar look and feel. Can the images be shown without using the anchor tag(s)? Do you know of any example source codes where something similar is done ? Can the solution be done purely without JQuery? Any help from you is greatly appreciated. Thanks!

    Cheers
    Nedave

  22. Hi,
    This is great! I am fairly new to javascript and your tutorial has made it very easy for me to understand the basic function of of this framework. I would greatly appreciate it if you could provide some assistance on this matter - how do I get this to show my content when the page loads and have it hide only when clicked? Here is the code that I copied and altered from your downloaded version and placed in my head. Thanks!!

    
    $(document).ready(function(){
    	$('div.toggler-c').show();
        $('div.toggler-c').toggleElements(
            { fxAnimation:'slide', fxSpeed:'fast', className:'toggler'} );
        $('ul.toggler-c').toggleElements();
    });
    
  23. Hi Nedave,
    Interface is no longer being supported. There might be some similar functionality in jQuery UI, but I haven't investigated it enough to know for sure. Perhaps you could ask about it at the jQuery UI Google Group

  24. That's great, clear and concise. Have bookmarked this article and will digest at leisure - thank you.

  25. Hi Karl,

    I have a very interesting question!
    Is it possible to get a (almost) similar navigation look as
    http://www.klm.com/travel/corporate_nl/corporate.htm
    with jquery?

    I mean the show/hide of the sub items in the navigation.
    1) they use mouseover, instead of .click
    2) after some minutes it hides itself.

    (I'm quit good with CSS, so that won't be any problem. I fancy it and I have a project coming up, so I'm looking for possibilities)

    I really think it's possible. But..
    What's you opinion?

  26. Love your script and have used it several times. I was wondering if there was an easy way to toggle left and right instead of up and down.

  27. Many people have been asking how to show and hide multiple DIVs. Here's the approach I use on my puzzle blog (see link in name) to toggle the rules of each individual puzzle, which even works when multiple sets of instructions are on the same page.

    THE HTML:
    1) Since we're dealing with two objects (a link that toggles, and a DIV containing the text to be affected), choose 2 different prefixes that will always be used throughout the site. For the link, just one prefix will be used. For the DIV containing the text, the two prefixes will be used together. (I only use the toggle approach for simplicity.)

    For my puzzle blog (see link in my name), I chose "puz" for the links, and "rules" to be used for DIVs, as described below.

    2) All the names in my links for opening puzzle instructions will, therefore, begin with "puz", followed by some unique identifier, usually related to the blog post itself. If I'm doing a September 2008 (09/08) entry on iPods, I might choose "puz0908ipod" as the class, as follows:
    <a href="#" class="puz0908ipod">Click here to see the rules for this puzzle.</a>
    (I'll be using classes in my examples, as I need to do it that way for my site, but IDs could also be used in this approach, as long as IDs work on your particular site.)

    2) The class name for the DIV will be the second prefix I chose followed by the full class name of the corresponding link. Since my example link class name was "puz0908ipod", and my second chosen prefix is "rules", the class of my DIV is named "rulespuz0908ipod":
    <div class="rulespuz0908ipod">The rules of this puzzle are this and that.</div>

    THE JQUERY:
    3) As in the original entry, we'll start by hiding any and all DIVs that contain rules in the first line after $(document).ready(), so that they're hidden upon document loading. Since they all have the same prefix (they all begin with "rulespuz"), this is simple in jQuery (newbies: the ^ means "begins with"):
    $('div[class^=rulespuz]').hide();

    4) Next, we need to create a function that operates anytime a link with a class that begins with our first prefix is clicked. In this example, we're looking for links that were clicked whose class begins with "puz", so:
    $('a[class^=puz]').click(function() {
    });

    5) Using a trick described in the "What is this?" post ( http://www.learningjquery.com/2007/08/what-is-this ), we start by creating a variable that wraps the link itself in a jQuery object:
    $('a[class^=puz]').click(function() {
    var $this = $(this);
    });

    6) We now need to get the name of the class of the particular link that was clicked:
    $('a[class^=puz]').click(function() {
    var $this = $(this);
    var x = $this.attr("className");
    });

    (So, if you clicked on a link with a class of "puz0908ipod", this function would activate, and the value of x would be equal to "puz0908ipod" - without the quotes.)

    7) Since we now have the class of the link, all we need to do is add the secondary prefix, and we can specify the class of the corresponding text DIV! In our example, x is "puz0908ipod", so the word "rules" + x returns "rulespuz0908ipod" as our selector. With our selector, we simply toggle:
    $('a[class^=puz]').click(function() {
    var $this = $(this);
    var x = $this.attr("className");
    $('.rules' + x).toggle(1000);
    });

    8) Two final touches. First, don't forget to end with return false, as this article describes, so that your site doesn't actually try and go to the link. Second, I prefer to change the code to let the person know that the rules can be hidden again. These changes result in the final code:
    $('a[class^=puz]').click(function() {
    var $this = $(this);
    var x = $this.attr("className");
    $('.rules' + x).toggle(1000);
    $(this).text($(this).text() == 'Click here to see the rules for this puzzle.' ? 'Click here to hide these rules.' : 'Click here to see the rules for this puzzle.');
    return false;
    });

    THE END
    That's it! You've now got jQuery code that can handle several links and their corresponding DIVs, without affecting any of the other links or DIVs, even ones that use the same prefixes (unless, of course, you've used the same exact className)!

    What happens if, say, later in this month, I do another entry concerning iPods? I might just use "0908ipods2" for the basic name, giving us "puz0908ipods2" for the link, and "rulespuz0908ipods2" for the corresponding DIV.

    Obviously, if you wanted to use IDs in place of classes, you would use 'id' everywhere I used 'class' in the code above, and change the dot in $('.rules' + x).toggle(1000); to a #, resulting in: $('#rules' + x).toggle(1000);

    • Antony

      Hi Scott

      This was really helpful, thanks.

      Instead of changing the text between 'click here to show rules' and 'click here to hide rules' I was hoping to use an image instead eg a right arrow if the div is hidden and a down arrow if the div is show.

      Can anyone help?

      Thanks

      Antony

    • mario

      thx Scot this was really usefull... i've mannage to incorporate that to my new site and it working like a charm! :-D

      now im looking to do the same with Multiple Fancy Drop Caps script that could be found also on this site :-)

      it is needed because the script is broken when you try to use it with some jquery tabs for example Each div tab container needs new id name... Is it possible to do something similar with this too?

      thx!

    • David

      Hello,
      Thanks Scott for this awesome and well explained tutorial. I'm a total newb to jQuery, but I was able to use your example to set up a simple four item horizontal nav whose links open and close their own divs.

      When clicked, my four nav links open their divs according to their position in the code - link 1 is at the top, link 2 opens underneath that, link 3 opens underneath that one, etc. The problem is, if someone clicks on link 3 while div 1 and 2 are open, div 3 opens "down page" which the user cannot see. Their only clue is that the vertical scroll bar changes to indicate there is more content if you scroll down the page.

      Is there a way to have the links close any currently open divs and then open it's own div? For instance, user clicks link 1 and div 1 opens. Then they click link 2 (or 3 or 4) and div 1 closes and div 2 (or 3 or 4) opens. Can your method handle that?

      I hope that makes sense. Thanks for any insight you can offer.

  28. Pascal

    From another newbie to jquery: thanks for the good work, Karl.
    And thank you Scott for the improvements.

  29. Blah

    A lambda function is an anonymous function.
    same, same but different.

  30. Fantastic articles - keep em coming. So easy to learn when you say it eh :)

  31. marc

    I apologize if this has been mentioned before, read through many posts, but after trying many approaches I just need to post the question, which is:

    How to use toggle with multiple links and divs (number of divs will vary). Each example I've messed with seems to depend on the hierarchy of the divs and/or using child selectors so that the div following the link directly is the one that toggles.

    I have a list of entries. The list is going to have the content pulled in and the number of entries will vary. Each entry is formatted into three columns; thumbnail, content, & "view/close" button column". The content column will have the "expanding" div to toggle. So there will be a header to click on in that column and then the button in the button column that when clicked will expand that same div nested in the content div.

    In short -
    How do I reference the divs independently with each new entry so that the content div expands when either of the links are clicked to toggle (the headline in the content column & the button), and the other divs still toggle?

    Probably a big question, but even just a link for reference would be great.
    Thanks

  32. Scott

    marc, my post (#130) shows an approach that could be easily adapted to your needs. It really only requires that any given div's class or id is a pre-determined prefix added to the class or id of the link.

    Even if the class/id names of the links are computer generated, such as "item0269", giving the content itself a prefix, such as "stuff" (making the content's class/id to be "stuffitem0269" in this example), shouldn't be a problem.

    It also won't matter where the links are in relation to their corresponding div. As long as the class or id names work out properly, it will work.

  33. marc

    Thanks for such a quick response, I will look at your post closer. Thanks again

  34. Jackson

    Hi, guys I have recently started using jQuery, i started working on the slideDown function, It is running perfectly, but the problem arises when there are many buttons. Suppose, if i press the first button the first page starts sliding down, but quickly before the first page loads completely, if you click the second button it shows you both the first page and the second page even though i have used the hide function to hide the first page. The following is the code that i have used...

  35. Hi Jackson,
    Sorry, but I had to truncate your comment. If you have short code snippets to include in your comment, please follow the guidelines above the comment textarea (marked important. If you have a lot of code or markup, especially lorem ipsum, please provide a link to another page that demonstrates the problem or issue you're discussing.

  36. Hi Karl and Scott

    I've tried using Scotts example, it's exactly the kind of thing I've just spent 10 hours (literally!) trawling the web for. So as you can imagine, I'm a VERY happy man at the moment!

    But I'm having some trouble getting it to work.

    This is my jquery:

    
    		$(document).ready(function() {
    		$("#eventlist li.[class^=sum]").css.("display","none");
    		$("#eventlist li.[class^=sum]").css.("width","100%");
    
    		$("li[class^=evname").click(function() {
    			var $this = $(this);
    			var x = $this.attr("className");
    			$("li.sum"+x).slideToggle();
    		});
    	});
    

    An example of the HTML that goes with this is:

    
      <li><a href="#">click here</a></li>
    		<li>show/hide some text here</li>
      <li><a href="#">click here</a></li>
    		<li>show/hide some text here</li>
    

    Any ideas why this isn't working for me?

    Thanks in advance.
    Andy

  37. Sorry guys, I didn't expect that!
    [...]

  38. John

    Hi, I'm using this technique to show one of two different divs depending on the selection of two radio buttons. For some reason my hidden divs are showing on page load, then disappearing. Other than that it's working correctly.
    Any thoughts? Thanks! John

    $(document).ready(function(){
    $('#freshman').hide();
    $('#transfer').hide();

    $('#clickShowFresh').click(function() {
    $('#freshman').show('slow');
    $('#transfer').hide();
    });

    $('#clickShowTrans').click(function () {
    $('#transfer').show('slow');
    $('#freshman').hide();
    });
    });

  39. Hi Guys,

    Just thought I'd let you know that I've solved the dynamic slideToggle problem for my site. I hope this example will help others of you to do the same.

    This is a development on Scott's work above, thank you Scott!!!! (Can't stress that enough!!)

    First, hide the elements you want to toggle between using CSS:

    
    li[class^='evname'] {
    	width:35%;
    }
    

    The CSS above is hiding any li with a class name that begins with "evname". YOU DON'T NEED THE DOT FOR CLASS as you would in normal CSS (this got me for ages!).

    Then the HTML looks like this. Please remember this is just my example and you'll probably have to edit it to suit you.

    
     <li class="evdate">10/02/09</li>
      <li class="evname01"><strong><a href="#" id="0">This is the event name</a></strong></li>
      <li class="evregion">South Wales</li>
      <li class="evloc">Cardiff</li>
      <li class="sumevname01">Some text here, this is what will toggle</li>
    
    <li class="evdate">10/02/09</li>
      <li class="evname02"><strong><a href="#" id="1">This is the event name</a></strong></li>
      <li class="evregion">South Wales</li>
      <li class="evloc">Cardiff</li>
      <li class="sumevname02">MOre text here that will also toggle.</li>
    

    In this example, all the data is dynamic and the number at the end of evname and sumevname is the uniqueID of the data set. There could be hundreds of these on a page and this example will always work.

    So, finally the jquery:

    
     $(document).ready(function() {
    
    		$("li[class^='evname']").click(function() {
    			var $this = $(this);
    			var x = $this.attr("className");
    			$("li.sum"+x).slideToggle();
    		});
    });
    

    If you can't get your head round this jquery, read post number 130 by Scott. His explanation is excellent!

    And that's it! Good luck!

  40. Hi and thank you for your useful examples and all of the help you give people! I have a question similar to another commenter. I have a div that is automatically populated with ten images through Wordpress posts, but I'd like to set it up so that only four images are showing with a "show all" link that will toggle the rest of the div open. However it can only be set up as one div as far as I can figure. It does have a fixed height though so I was wondering if I could set up the slide effect to only show a certain percentage of the div and have the remaining amount hidden to be toggled. Do you think that's possible?

    Thank you!

  41. Karl,

    I hope it is not too late to ask questions on this section. I recently purchased your book on Learning jQuery and am playing catch-up. Great stuff and I really appreciate this tutorial because it is exactly what I was looking for. Thank you.

    I need to push this one level further and could use a little guidance. I am working on a project that dynamically returns several tables of data. I would like to have the table headers show when the page loads but keep the table data portion hidden. This works fine and works on multiple tables. You can see the sample here: http://editorschoicemusic.com/flash/jq_test.html.

    However, I would like to limit the slideUp/slideDown function to the data portion of each specific table. Each table has its own toggle button. I have given each table the same class name as these tables are loaded dynamically, but still need to act on each individual table. I am confident that jQuery can do this kind of task, I just am not versed enough to know how at this point. Any guidance you can provide would be greatly appreciated.

    Thanks again for the great resources.

  42. Hi ho,

    First, thanks so much Karl (and friends) for all the wonderful tips in Learning jQuery!

    I was tinkering with a pared-down version of the Slicker Show Hide, and noticed in Opera 9.6.2 , even with the
    $('someElement').hide();
    as the first line after my
    $(document).ready(function() {
    I'd see the block I intended to toggle "flash" on the screen whenever the page was refreshed. I tested this in FireFox 3.0.3, Chrome 0.3.154.9, IE 7.0.5730.13, Safari 3.1.2 and Flock 2.0, and it only happens with Opera (all on Windows XP).

    As a workaround, I changed the display:block in the style sheet to display:none for the element I was trying to toggle and the "flashing" problem went away. The show and hide toggle still works perfectly in all the broswers above - just no more annoying flash on page-load. Now if I could just get my accordian menu to not flash when the page loads, I'd be golden! ;)

    Anyway, hope that helps, and thanks again for your tips here.
    -JeffK

  43. Hi Jeff,

    That "flash" of content can be really annoying, for sure. The problem with setting display: none in the stylesheet is that users without JavaScript won't be able to see the content at all. I wrote about a way to get around this in a recent entry. Hope it helps.

  44. Hi ho,

    Thanks for the speedy reply! I agree that display:none is not the greatest for this (it just makes no sense, ya know?), but at least for my case it still works...

    Here's the deal - I did my page design before I got around to adding search functionality, and I just couldn't come up with a good spot to tuck a little input box into the design now that I'm fiddling with search abilities for the site. Thanks to jQuery, I can slide the input box in when needed thus keeping the design "clean" as far as I'm concerned.

    As for the Javascript disabled users (do folks really browse without JS anymore?), I just tossed a noscript tag into the same element that toggles the input box, and that takes the no-JS folks directly to the search.asp page instead of sliding things around on the current page.

    I'll go have a looksee at the awesome way to make the flash not so flashy.

    -JeffK

  45. Luke Wilson-Merrill

    Hi

    I am new to Jquery but I am profiscient in xhtml/css. It may be a small thing but I tried your Slick show hide tutorial and it will not show hide. I am wondering what I am missing:

    
    <script type="text/javascript" src="jquery-1.2.6.pack.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)
            $('#content').hide();
           // shows the slickbox on clicking the noted link
            $('a#slick-show').click(function() {
              $('#content').show('slow');
              return false;
            });
           // hides the slickbox on clicking the noted link
            $('a#slick-hide').click(function() {
              $('#content').hide('fast');
              return false;
            });
            $('a#slick-toggle').click(function() {
              $('#content').toggle(400);
              return false;
            });
    
          });
    </script>

    I altered the selectors and that's about it. I added this to the xhtml

    
    <div id="showhide">
                            <a href="#" id="slick-show">Show</a>
                            <a href="#" id="slick-hide">Hide</a>
                            <a href="#" id="slick-toggle">Toggle</a>
          </div>
    <div class=".navcontainer0" id="showhide">
      content goes here
    </div>
    

    For some reason, the show/hide/toggle isn't showing/hiding or toggling when clicked. Any

  46. Hi Luke,
    It looks like you're trying to hide/show/toggle a div with id="content" but your div actually has id="showhide"

  47. Luke Wilson-Merrill

    I appreciate the response Karl. But I made an error with my initial layout of the code. The "id=showhide" within the <div> containing "class=navcontainer0" was supposed to be "id=content". I'm still tinkering with it.

  48. Zed

    Im trying to have a tag automatically fade in once the tag is called. What am I doing wrong?

    $(document).ready(function() {
    $("p#1").show(1000);
    $("p#2").show(1500);
    $("p#3").show(2000);
    $("p#3").show(2500);
    $("p#4").show(3000);
    $("p#5").show(3500);

    });

    p { background:white; }

    Test 1
    Test Sub Level
    Test 2
    Test 3
    Test 4
    Test 5

  49. Erik

    I would like to use the show hide function within an image map, is this possible? Since image maps use an id I cant get it to work.

  50. LOVE IT! LOVE IT! LOVE IT! LOVE IT! LOVE IT! LOVE IT! LOVE IT! LOVE IT! LOVE IT! LOVE IT! LOVE IT! LOVE IT! LOVE IT! LOVE IT! LOVE IT! LOVE IT! LOVE IT! LOVE IT!

    Seriously... how many times can I say that before I become obnoxious? I don't care if I come off as obnoxious in this case... because I LOVE IT!

    I use the toggle option as a link to open a box with more info, and then inside the box, I add the hide option as a "close" link. love having the option to either toggle using the original INFO link, or close using a "close" link that is only seen when the box is open.

    LOVE IT!!!

  51. Rori

    Hi, greet script but i have a strange problem with it.
    I include it to my page but it give me a strange error.I look it at the JS Console
    and i got that error:
    $(document).ready is not a function
    at line 64, and here is the code ...

    
    	$(document).ready(function() {       //  line 64 ?!
    		// hides the slickbox as soon as the DOM is ready (a little sooner that page load)
    		$('#slickbox').hide();
    
    		 $('a#toggle').click(function() {
    		  $('#slickbox').slideToggle(400);
    		 return false;
    		});
    	});
    

    I loaded the jquery at the header.
    Do someone know what may be the problem.I spend almost 2 hours looking at it.And can't find the mistake ?!

    Thanks.

    • You need to make sure that the jquery file is being included in a script tag before your custom script. Make sure that you're pointing to the correct file path and name. Try this one:

      <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>

  52. Rori

    Thanks Karl, It's strange but my jQuery is loaded, I used the console to see that ( console.log("msg"); ) but when i moved the part in to the tag. The script started to work.But when it is in to the it's not working.

    I think that the problem is in that $(document).ready part, but i don't have the time to view why.
    I will leave it like that for now and may be later will try to fix that.The main thing now is that it's working.

    Thanks for the help, and the script.

    PS.
    If u know why this is happing (the document part) you can explain it to me :)

    • Glad you have it working one or another, but it's still a little odd that the document ready code is flaking on you. Are you loading another JavaScript library, such as Prototype or Mootools? If you put up a public page demonstrating the problem and post a question to the jQuery Google Group, I'm sure someone can help you.

  53. Rori

    Hey, Karl i fix the problem.It was so simple.The problem was really the mootool that I used.Couse the mootool and jquery use the same $().
    jQuery have a little func. to fix the problem noConflict()

    And the code will look something like that:

    var $z = jQuery.noConflict();
    $z(document).ready(function() {
        // hides the slickbox as soon as the DOM is ready (a little sooner that page load)
        $z('#content').hide();
    
        $z('#toggle').click(function() {
                      $z('#content').slideToggle(400);
                      return false;
          });
    });
    

    And now the jQuery will work fine with Mootool.The same is for prototype and other JavaScript Framework using $();

    That's from me for now.Thanks for the help.And I hope that I helped to anyone who will or have the same problem.

  54. Robby

    Hi,
    I have the multi Slicker Show/Hide working ok with an href but after applying the class link1 to a check box it never shows the check mark(tick) but rest of it works . . any clues ?

     Transport1 
  55. Robby

    Hi,
    Thanks I solved it . . take out the return false statement . . . Duh !

  56. Sliding menus look aesthetic, and it has a lot of role to play in UED as well. Makes website look compact, even with lots of information hidden at the tip of the mouse!

  57. Adam

    I'm fairly new to the Jquery/javascript world and was wondering if I could get a hand in how to implement this. Currently I am dynamicaly creating a table were i am giving each tr a show/hide capability for a div that it contains, using a plugin, but it has a few quirks I dont care for so I would like to attempt to use this method of doing it. Below is how I am adding the effect currently, and I am really not 100% possitive how to do the same thing with your example.

    $(document).ready(function() {

    var counter = 0;
    $('#employerParent tr').each(function() {
    //animatedcollapse.addDiv(counter, 'fade=0,speed=400,persist=0,hide=1');
    counter++;
    });
    animatedcollapse.init();
    });

    Employer Parent is the name of the table, and the counter is the ID that is being added to each table row and div dynamicaly. So basicaly when I create the table rows, each row gets a OnClick="javascript:animatedcollapse.toggle(counter)" and each div created in that row has an ID that is equal to the counter.

    So what I need to figure out is:

    1. How do i use the loop for every record approach to add this effect to each row?
    2. What new code would replace the OnClick event of my table rows?

    Thanks a bunch in advance

  58. Marco

    Hi Karl, im working on a Intranet page and i found your code really heplful, thanks, i just have a little issue, everything works just fine on Firefox, but i just cant make it work on IE6.0, the div content which is suppose to be hidden is being showed, somehow the script seems to work in a kind of way because when i click on the links all the content moves a little.

    Any of you guys had some problem like this? is there a work around for IE?

    Thanks for your help

  59. Deb

    Hi Karl,
    Not sure if you are still answering comments for this exercise and I'm wondering if you could help me out? (love this site btw. I'm using it and an older "Learning jquery" book to get my head wrapped around concepts. Slow going and I must be sick or stubborn in trying to figure things out...lol.

    Anyhoo. I have this code so far:

    
    $('#summary div.story').hide();
    $('a.more').click(function() {
    	$('#summary div.story').slideToggle('slow');
    	$(this).text('Read it later');
    });

    These are the words that are present when the page first loads:
    <a href="#" class="more">Read the Full Story</a>

    And my goal was to have it change to "Read it later" (or some such) when the link is clicked. Which right now, it does.

    What I can't figure out it is how to have "Read it Later" change back to "Read the Full Story" when the hidden div toggles back to hidden.

    I hope my question makes sense.

    And, I'm using the expander plugin elsewhere (which was a great google find. I wrote you recently to thank you for that ;-)

    Thanks,
    Deb - jquery newbie.

  60. Hi Deb,
    Sorry for the delay in getting back to you. Here is a little additional code that should do what you need.

    $('#summary div.story').hide();
    $('a.more').click(function() {
      $('#summary div.story').slideToggle('slow');
      if ($(this).text() == 'Read it later') {
        $(this).text('Read the Full Story');
      } else {
        $(this).text('Read it later');
      }
      return false;
    });

    It could be shorter, optimized, abstracted etc., but it should work as is.

  61. Williams

    開啟 關閉

    hi
    if i have 10 group's show and hide,
    how to let the jquery work ,
    Thanks.

    this is my code,
    but not work!

    $(document).ready(function()
    {
    for (i=1; i<= 10; i++)
    {
    $('a#slick-show' + i).click(function()
    {
    alert('#content' + i);
    $('#content' + i).show('slow');
    return false;
    });
    $('a#slick-hide' + i).click(function()
    {
    $('#content' + i).hide('fast');
    return false;
    });
    }
    });


    Show Hide
    content1...
    Show Hide
    content2...
    Show Hide
    content3...
    .
    .
    .

  62. Haarball

    Hi, what would I do if I wanted the text that toggles the box to change upon toggle? Going from saying "Expand" to saying "Contract", for instance. Thanks for a wonderful tutorial!

    • Hi Haarball,
      You would do something like this:

      $(document).ready(function() {
        // toggles the slickbox on clicking the noted link
        $('a#slick-toggle').click(function() {
          if ($(this).text() == 'Expand') {
            $(this).text('Contract');
          } else {
            $(this).text('Expand');
          }
          $('#slickbox').toggle(400);
          return false;
        });
      });
      
  63. Todor Rangelov

    Bug problem with expand input and make cursor focus!?

    So Im trying to make toggle div whitch contain serchbox input. And after expand the focus cursor to be auto addaded.

    Could somebody help me becouse tne curosor is not present.

    Example code:


    $(document).ready(function() {
    $('#slickbox').hide();
    $('a#slick-toggle').click(function() {
    $('#slickbox').toggle(200);

    $('#s').focus();

    return false;
    });
    });

    Seacrh

    <form name="searchform" method="get" id="searchform" action="/">

  64. Love this, nice one Karl!

  65. Really than to the Author. I got what I was looking for

  66. Justin

    Hey, great stuff, i've used your site for several jquery tips.

    Just trying to take my jquery toggle to the next level and wanted to add a (-) or (-) to my toggle link, depending on the state of the toggle. I saw an example earlier in your comments, but when i tried to use it, it keeps appending a new copy of the text every time I click. Any suggestions? Thanks!

    
      $('#mem_cat').hide();
      $('#mem_cat_click').click(function(){
    
      if ( $('#mem_cat').is(':visible') ) {
        $(this).append('(-)');
      } else {
        $(this).append('(+)');
      }
    
        $('#mem_cat').slideToggle(); return false;
    
  67. Hey, Karl

    First off I would like to say thanks for the amazing resources and information you guys put up on this site. You guys do a great favor for jscript noobs like myself.

    I have a question for you regarding the Jquery slide toggle effect, I was hoping you could push me in the right direction. I have this Toggle effect that I have implemented successfully, using an H2 as the trigger and a Div with a Class as the Toggle Container. What I would like to do is have a separate trigger per se that would be nested is the toggle_container div, that would be able to close the container that it is in. Is there any way of doing this easily?

    My code looks like so:

    
    HTML:
    
    <h2  class="trigger"> <a href="#"> Click for more Details </a></h2>
    
    <div class="toggle_container">
    
       Toggle Content: Duis aute irure dolor in reprehenderit
       in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
       Excepteur sint occaecat cupidatat non proident, sunt in culpa
       qui officia deserunt mollit anim id est laborum."
    
       <h2  class="trigger"> <a href="#" > Click to close </a></h2>
    
    </div>
    
    JSCRIPT:
    
    //
    $(document).ready(function(){
    	$(".toggle_container").hide();
    	$("h2.trigger").toggle(function(){
    		$(this).addClass("active");
    	}, function () {
    		$(this).removeClass("active");
    	});
    	$("h2.trigger").click(function(){
    		$(this).next(".toggle_container").slideToggle("slow,");
    	});
    });
    

    Unfortunately the link nested inside the toggle_container does not work because it the H2 can only trigger the Div when it is outside of the Div.

    Not sure how to implement the solution via Jscript.
    Suggestions?

    Any help would be greatly appreciated.

    Btw I've searched for a while trying to find a solution to this to no result.
    Might be a good topic to touch on as jquery noob tut.

    Thanks,
    VP

    • Hi Chris,
      First of all, I'd bind the click event to the links rather than the h2 elements. You can give them display: block; if you want the click to extend to the whole h2 area (and in an IE6-only stylesheet, give them zoom: 1;).

      Then, give the interior link a class of "close" to distinguish it from the other one.

      Your jQuery script can now look like this:

      $(document).ready(function() {
        $('.toggle_container').hide();
        $('h2.trigger a').click(function(){
          if ($(this).hasClass('close')) {
            $(this)
              .parents('.toggle_container:first').slideUp('slow')
              .prev('.trigger').toggleClass('active');
      
          } else {
            $(this)
              .parent().toggleClass('active')
                .next('.toggle_container').slideToggle('slow');
      
          }
      
          return false;
        });
      });
  68. How can I combine the slide with hoverIntent? Trying to make a meganav that slides up/down.
    Thank you!
    ~ Jim

    • Hi Jim,

      At its basic level, the hoverIntent() method works just like jQuery's hover(), taking a mouseenter and a mousleave argument. So, you could do something like this inside a $(document).ready() function:

      $('some-selector').hoverIntent(function() {
        $('some-other-element').slideDown();
      }, function() {
        $('some-other-element').slideUp();
      });
      

      In this situation, it would make sense to put both the hoverable element and the element you want to slide up and down within the same container element and attach the hoverIntent to that container. That way, when you mouse into the "meganav," you won't be mousing out of the element that you've attached hoverIntent to.

  69. Thank you for these simple examples :-)

  70. Hi Karl - thanks for such as easy to follow, simple example of the jquery show and hide function. How would I go about opening a new browser window on the same click as the 'show the box' click though - so that it shows the box and open's a window (for a specified) url? Thanks :)

  71. Dan

    I am having trouble floating 4 lists within the div that's hidden. When I float the ul's and then expand the div, the div expands but never goes back up again when you try to close it. It just stutters and reloads the div opening it again instead of smoothly closing back up again. I have had a trawl through the comments but can't find a similar problem.

    Thanks for any help, your sites a lifesaver!

  72. Frederic

    Neat show hide !

    What if I wnat to apply it on multiple link / div in the same page ?

  73. Josh Craddock

    Hey,

    Is there a way to make it "stick" at the top upon click?

    http://hostpear.com/2/ If you click on "Packages" on the right hand side, it slides down to the id. I want it to stay at the top..

    Thanks

  74. John

    Hey there. Awesome tutorials, love the site, but i'm having some trouble with this.
    To my understanding i'm not doing anything wrong.

    I am trying to have a content div that hides and shows another content div in the same place on hitting a toggle switch, and vice-versa. Here's my script:

    $(document).ready(function() {
    $('div#contentWrap2').hide();
    });

    $('a.toggle1').click(function() {
    $('div#contentWrap2', 'div#contentWrap1').toggle('fast');
    return false;
    });

    halp!

  75. John

    err. forgot to say what happens... I can see that it hides the second content div and leaves the first in place, but the toggle switch doesn't do anything. =/

  76. Glen

    Had an issue using a checkbox to toggle the sliding div. The tick was not appearing in the checkbox when clicked but the toggle was happening. The solution was to change the the event from 'click' to 'change' so that $('#slick-slidetoggle').click(function() became $('#slick-slidetoggle').change(function()

    Hope this helps anyone with the same issue.

    • Mattias

      Dear Karl and other contributors,

      First of all I like to thank you for this wonderfull tutorial.
      I have implemented this without actual problems, though there's one small issue I'd like to get rid of.
      In IE7, the font from the #slickbox div is different from all other text on my page.
      I see it happen on all pages where I use this Jquery toggle, as a matter of fact, I see it happen on this page ass wel.

      The text in the line "This is the box that will be shown and hidden and toggled at your whim. :)" is lighter than other text, kinda like the difference between Clear Type on/off.

      I was wondering if something can be done about that?

      • Adyonthebeach

        This bug is caused by the css filter attribute being added to the actioned DIVs style.

        To resolve this issue add a callback function to the JQuery toggle method i.e

        $("#mydiv").toggle(500, removeFilter);

        and add the callback function to your javascript which removes the filter attribute from the DIV.

        
        function removeFilter() {
        this.style.removeAttribute("filter");
        }
        
  77. John

    Newbie with a question.

    I have an asp dropdown list, and need to show/hide certain divs based on the selection. What's the easiest way to go about this? Thanks in advance

  78. Thanks for posting. This is exactly what I was looking for.

  79. Holian

    Hello!

    I try your example.

    The address is http:\\localhost\test.php

    After i hit the the link, my address will be: ....\test.php#

    test

    Could you help me how can i fix this?

  80. Dean

    Hey Karl,

    Thanks for this. This tutorial was enough to make me bite the bullet that i've been avoiding called jQuery.

    Can you show how one would be able to use cookies to remember the state of the box when using the toggle?

    I can manage the cookies but i cannot see how to get the current state when toggling.

    thanks,
    dean

  81. handoyo

    Hi,thanks a lot for the tutorial.I want to ask,is it possible to automatically hide the box when we have done inserting text on the box?Thanks..

  82. Matt T

    Hi,
    Great site, loads of really cool tips.

    I've used the slide toggle code. I need a solution that allows me to swap a image from a plus to a minus depending if I need to open or close the slidebox div, you have a simlar solution in your q and a but that applies to a css style

    I am using this code to try and get this image swap to work as part of the slidetoggle function. I can get the if statement to work but cannot get the else statement to revert the image back to it's original state.

    var imageEle = document.getElementById('slick-slidetoggle2');
    if(imageEle.innerHTML = '') {
    imageEle.innerHTML = '';
    }
    else {
    imageEle.innerHTML = '';
    }

    I have also had to duplicate the slidetoggle function so it work if i click on two seperate elements, say for example text and a image. Is there a work around so I don't have to duplicate the function and still apply it to seperate elements?

    The sample page can be found here:
    http://www.richardheald.com/loadrunnerhtmltest/slickbox.html

    • Matt T

      Sorry didn't see the code tag warning,

      
      $('#slick-slidetoggle').click(function() {
          $('#slickbox').slideToggle(1000);
      	var imageEle = document.getElementById('slick-slidetoggle2');
              if(imageEle.innerHTML = '<img src="images/plus.png" width="17" height="17"&gt') {
      		imageEle.innerHTML = '<img src="images/minus.png" width="17" height="17"&gt';
              }
              else {
                      imageEle.innerHTML = '<img src="images/plus.png" width="17" height="17"&gt';
              }
          return false;
        });
      
  83. Mike

    Hi. I am also a newbie and just learning jQuery. You did something on this page that I would like to do, but can't seem to replicate in my code - which is you hid a div at the time the page loaded using:

    
    $(document).ready(function() {
           // hides the slickbox as soon as the DOM is ready
           // (a little sooner than page load)
            $('#slickbox').hide();
     });
    

    I am trying to do the same thing... hide multiple divs at load and show them depending on what is selected in a select box, but I can't even get the hiding to work. Help?

    I have copied your syntax, but it doesn't seem to hide when loaded.

    Thanks

  84. Mike

    Nevermind, I figured it out. Thanks for your code examples!

  85. Adam

    Hi Guys,

    I am a complete noob to jQuery! I am having troubles getting this to work...well actually, I can get the toggle to work alone but not when I have another jQuery effect on the same page (http://www.dynamicdrive.com/dynamicindex14/fadeinslideshow.htm).
    I have an idea that its something to do with the compatibility of the two effects, i.e. I'm not calling them properly in the html. I am tearing my hair out, can someone help me out?!
    My test site for this is http://www.farlie.org, I havent styled it much yet, Im just trying to get the functionality of it going!

    Cheers in advance!

  86. Adam

    For some reason I can only get the toggle to 'bounce'!

    I know Im super close, can anyone lend a hand?!

    Adam

  87. AJA

    Howdy there, a fine and helpful article you have here. As this is an old post, you may already have run across the answer to this question, but

    I don't know why it's also called a lambda function. Can someone enlighten me?

    the reason why it's called a "lambda function" stems from Alonzo Church's "Lambda Calculus".

    Originally Church designed the lambda calculus to look into the core of mathematical reasoning, and focuses on the definition of functions (from a mathematical point of view).

    Lambda calculus was part of the original inspiration for LISP, and is functionally based -- hence forms the basis for functional programming languages, and a great many basic programming concepts. In lambda calculus, as in LISP and Scheme, and other functional languages (Haskell, Erlang, etc.) functions are first class concepts, like addition, and even identity, ( if I have a function that says

    function (arg) { return arg; }

    that would be the identity function, (trivial, yeah).

    Another primary result of Church's system is that functions need not be named to be used, these are lambda functions for example if I have two variables v and u and I want to add them, I can say:

    function adder(v, u) { return v + u; }

    or I can just say:

    function (v, u) { return v + u; }

    and we can take the result from context rather than adding another definition to the namespace.

    I hope that makes things clearer!

  88. Sunny

    Karl, thank you for the wonderful articles. You're the man!

    Great Scott! Thank you for the example regarding handling dynamic data.

    If any others are struggling with dynamic pages re: Scott's example, you need to read up on jQuery Selectors - Attribute Filters. Good luck.

  89. A M A Z I N G !!!
    I'm a newbie on javascript but it worked pretty fine for what i needed. I still have to figure out a couple of things so this runs propperly and do exactly what I want, but so far it is a beautiful code. you can check it out in http://www.enrgb.com/pruebas/sandrosellini/

    Gimmie some skills maaan!

  90. Mark

    There's another video tutorial I've just found which explains how to do it independently: http://www.sebastiansulinski.co.uk/web_design_tutorials/tutorial/52/show_and_hide_div_with_jquery

  91. David

    Sorry for the double post. I replied to Scott's awesome example above (September 7, 2008) and my comment is buried way up thread. If anyone can offer help on modifiying his tutorial, I would appreciate it!

    From above:
    Hello,
    Thanks Scott for this awesome and well explained tutorial. I'm a total newb to jQuery, but I was able to use your example to set up a simple four item horizontal nav whose links open and close their own divs.

    When clicked, my four nav links open their divs according to their position in the code - link 1 is at the top, link 2 opens underneath that, link 3 opens underneath that one, etc. The problem is, if someone clicks on link 3 while div 1 and 2 are open, div 3 opens "down page" which the user cannot see. Their only clue is that the vertical scroll bar changes to indicate there is more content if you scroll down the page.

    Is there a way to have the links close any currently open divs and then open it's own div? For instance, user clicks link 1 and div 1 opens. Then they click link 2 (or 3 or 4) and div 1 closes and div 2 (or 3 or 4) opens. Can your method handle that?

    I hope that makes sense. Thanks for any insight you can offer.

  92. Hi Karl, thanks for this great tutorial. It works like a charm!

  93. Seb

    Hey Karl,

    In the first instance I need to thank you for this lovely script that you shared with us, morons :).
    I managed to make this script work properly on my custom WordPress theme, but my problem is that I need an extra feature.

    So I have two buttons ( coded nicely in CSS ): one is to open the content on a particular page and the other one is to close the content ( the one that closes the content is located inside the closing div, just for the record ).
    I only want the button that shows the content to disappear while the proper content is loaded ( and logically to 'come back' when the content disappears ).
    The idea here is to set somehow an extra style to the opening button ( display: none; ) when clicked and to make that extra style to disappear. I'm not a guru in JS, I barely know some basic things ( this is why posted this help-requesting comment ), but I have the starting thing :). I sure that you can come up with a better idea or at least with a solution.
    I also need to mention that the whole page elements ( divs especially ) are positioned absolute from CSS ( maybe this is a important thing as well, I don't know ).

    I will be really, really thankful if you could provide me a solution to my problem as soon as possible :)

    Thank you,
    Sebastian

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

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

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

Leave a Comment

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>
  • Use &lt; instead of < and &gt; instead of > in the examples themselves. Otherwise, you could lose part of the comment when it's submitted.