Slicker Show and Hide
read 288 commentsLast 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:
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":
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.
- // hides the slickbox as soon as the DOM is ready
- // shows the slickbox on clicking the noted link
- return false;
- });
- // hides the slickbox on clicking the noted link
- return false;
- });
- // toggles the slickbox on clicking the noted link
- return false;
- });
- });
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
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:
- Accordion Madness
- More Showing, More Hiding
- Slicker Show and Hide
- Basic Show and Hide
- jQuery UI Accordion
















First of all I want to say thank you for such good tutorial... :)
I have no problem with the code but I had a question if you could help me with... I have an anchor link that takes you to a section where I've applied this show/hide feature. What I want to do is when a user clicks on the anchor link it should take them to that section and open the closed div. Is there a way to do this? I would really appreciate if you/anyone could help me with this!
Hello,
"when a user clicks on the anchor link it should take them to that section and open the closed div."
To do this, simply implement the advice on the post above to reveal the div, and within your anchor link use the "a name" tag to allow the user to jump to the div at the same time. I guess it should work
More info on this tag can be found here:
http://www.w3schools.com/html/tryit.asp?filename=tryhtml_link_locations
By the way, thanks for all the articles Karl.
All the best.
Hello, thanks for the code. And sorry for my english.
What if we try to hide/show dinamic content like in a large list?
For example:
- Item 1
hidden content 1
- Item 2
hidden content 2
.
.
- Item n
hidden content n
This should be quite simple. You can have your divs layed out like this:
<div id = "slickbox1" style = "display: none;"><div id = "slickbox2" style = "display: none;">Then do a href to your text to a javascript function
<a hef = "javascript:toggleme(id);"> hidden text </a>
Where id is your slickbox id value, however you are dynamically building it.
The javascript function would be something like this:
function toggleme(targetId) {
$("#" + 'slickbox' + targetId).toggle(400);
}
You can use this structure for whichever slickbox method you'd like.
How can you make the slickbox1 and slickbox2 hide by default? The original script doesn't work with this structure.
Please advise, thanks.
Is there a way to show all hidden sections with just 1 link?
In my code I have 2 table rows that have hidden content (see code).. what I want to do is create a link that can open hidden content in both rows. At the moment I have to click on individual links to open their hidden content. It's just a "Show All" content feature I'm trying to add to the site. Any help is appreciated!
Test Link 1
Hidden Content ...
Test Link 2
Hidden Content ...
It's quite simple.Instead of using id tag use class tag for both your elements.
then instead of
use
this way you can hide as many element as you wish
I am a designer trying to make this work.
I have copied and pasted from your code but doesn't work.
So I link to slick.js in the HEAD?
And the jQuery library?
Do I need to create my own css as well?
as far as I know hide() show() and toggle() just adjust div size from zero to you defined size
let's say that you have div width 200px and height 100px
it sipmly start thread for adjusting width and height from 0 to 200px
try define width height and background color
put display:none; if you want to use show()
Yeah, someone neglected to tell you to download jQuery.js. Ok, maybe it's obvious to many developers but if you're a designer looking for extra flare. You'd break your head trying to figure out why it's not working!
Cheers and here is what you need to link in your
Download jQuery NOW!
your way of presenting tutorial is very poor man...i love your tutorial but i cannot implement...you should attach source files....hope you will do it next time...
Thanks
Sorry that this free tutorial written nearly four years ago did not meet your expectations. I hope you find what you're looking for elsewhere.
hey karl! Great tutorial! I've been looking for a nice animation to slide in my divs and your's works perfectly!
I've got 1 little question though:
How can make several divs show/hide? The above code applies to 1 div, but what if I have multiple divs with different content and i want to show them seperately when someone clicks on a link? I've tried making multiple divs, but it either shows all the divs or doesnt work at all.
Im not a webdevelopper, so sorry if my question is a bit stupid :)
Hello Karl
Once again, nice work on the tutorial just what I was looking for. Apologies if my question is in the wrong neighbourhood:) I am trying to marry flash and jquery into browser bliss. My query...... I would like to trigger demo 1's 'toggle the box' from a button inside a swf, I am using AS2. I've discovered that external interface call would be suitable for achieving this. P.S - I am very new to jquery.
Any help/ examples would be greatly appreciated. Thanks.
Hello Karl
Sorry for posting twice, I just realised my mistake.
Once again, nice work on the tutorial just what I was looking for. Apologies if my question is in the wrong neighbourhood:) I am trying to marry flash and jquery into browser bliss. My query...... I would like to trigger demo 1's 'toggle the box' from a button inside a swf, I am using AS2. I've discovered that external interface call would be suitable for achieving this. P.S - I am very new to jquery.
Any help/ examples would be greatly appreciated. Thanks.
Hi Jim. I was searching for a solution to my problem when I found your comment. I'm having the same issue as yours, except I need to fix this only on IE and Chrome. How would I trigger a jQuery click event (for a modal box) on a HTML anchor link with an animated flash movie inside? This works fine with FF and Opera, but not in IE and Chrome though. Anybody who can help? Thanks.
Hi! Great script... I'd just like to know what code I should add if I am having multiple contents going to be hidden and shown differently in one page, BUT I don't want to just copy and paste the .js code and rename it 1-2-3--n... you know what I mean?
For example:
Pseudocode
[div class="content1"] Content 1 texts
[a class="toggle content 1"] toggle 1
[div class="content2"] Content 1 texts
[a class="toggle content 2"] toggle 2
[div class="content3"] Content 1 texts
[a class="toggle content 3"] toggle 3
How do I use array? Not really good in JS, so if you can help, that'll be great
I meant:
[div class="content1"] Content 1 texts[a class="toggle content 1"] toggle 1
[div class="content2"] Content 2 texts
[a class="toggle content 2"] toggle 2
[div class="content3"] Content 3 texts
[a class="toggle content 3"] toggle 3
Nice tutorial. good examples, just trying this instead of using prototype for everything. Am loving jquery at the moment
it's called a lambda function because anonymous functions come from a form of mathematical computation called lambda calculus, birth place of most of the functional programming paradigm.
Further, lambda calculus involved recursive mathematical formulas, hence the reason reusable 'functions' as we now know them became useful.
Hi, great tutorial, I'm a newbie, but I'm getting it (mostly). I'm trying to use the toggle to display wp comments. I'm just working on my layout right now (have not begun inserting wp markup), but when I repeat the comments section for multiple articles displayed on one page, all comments sections slide! I just want the one comment section to slide that pertains to the article the user is clicking on, but I need to use a single class. Any suggestions?
Check out the page here: http://www.andreachristensen.com/wp-content/themes/andrea2010/layout.html
Andrea,
Your current toggle code,
$("div.commentwindow"), selects *all*div</codes on the page withclass="commentswindow", as you already know.To select only the
divwithclass="commentswindow"under the section you selected, you need to give the jQuery selector a context -- an indication of where in the HTML it should start looking for thediv.commentswindow. Without a context, it starts at the body, and finds a bunch of them. You set a context for jQuery by providing a second argument in the$()function:$(element-to-select, context-element).You want to set the context to the comment block in the current article. In your markup, the best element for that is
div.commentswrapper.Since that element is above the element that has the click function, you need to travel up a couple of levels:
parents()is a jQuery function that finds all the parent elements of the element it's called on. If you give it an argument (a value inside the parens), that's used to filter the parents, only selecting those that match. In your markup,div.commentsnav, the element with the click handler, has these parents:div.commentsban < div.commentswrapper < div.articlewrapper < div.articlebody < td.body <tr < tbody < table < bodyUsing
parents()on its own wuld have selected all those elements,. Applying a filter likeparents("div.commentwrapper")makes it soparents()only selects a single element, thecommentswrapperyou want to use as your context.I hope this helps...
- Val
Hi Val - Would you mind posting what that code would look like in full?
I'm trying to incorporate it into a page and I can't get it to work...
Thanks for your help.
Alex
Wow. this tutorial is so poorly written. It's almost as if it was written over four years ago.
Hahaha. That's pretty funny.
Great tip! I wonder if you can help me though, I tried this only putting the unhide function on radio button inputs. In other words, $('input#slick-show').click(function(). (When you select a certain option it reveals additional form fields). It works great except that once you select a radio button it doesn't let you select a different one if you chose it by mistake. (At least not easily, you have to click the one you want about 10 times and then it will behave). Is there a known conflict with radio buttons or any type of input tags?
Any help you can provide would be amazing... Thanks!
Try changing the "click" bits in the JS to "change" and you should have more luck. Have fun!
Altho what I just suggested might cause issues with ie6... I found a helpful bit of code on Stack Overflow that helps with the issue however:
Source: http://stackoverflow.com/questions/208471/getting-jquery-to-recognise-change-in-ie
I love this tutorial, but I am completely new to jQuery so need a little help.
I put the following code in a jQuery document named showhide.js
Then in an HTML page where I would like the box to function, I inserted the following code:
However, although there were 3 links and the text, the box didn't actually function. What am I missing?
Thanks,
Denys
It looks like you're missing the IDs on the <a> elements.
This is just what I'm after but I'm new to jquery and have a problem. I want to get this to work on a form with a checkbox (so that when checked an additional part of the form appears).
However, the tick in the checkbox does not show when chosen (the new form part toggles on an off fine). I've tried applying the id to the checkbox through various methods but cannot get it to work. Any ideas, Many thanks.
I too am trying to apply this to a checkbox to toggle a hidden section in a form. It works just fine to open and close the section but the checkbox doesn't show as checked when toggled.
Any ideas would be greatly appreciated.
slickbox = id of the div to hide / show
checkboxid = id on the checkbox that triggers the event
Is there a plugin for slikbox plugin for wordpress.... and can i customize it to resize accordingly with the size of content .please let me know as i want to use it my website http://alalawa.com/
This is cool! Just what I need. Is it editorial use only, or what that's called? Commercial something... ?
You may use it however you wish.
Thanks for script.
I have a problem. I have implemented everything fine into a div, however when I open up the slidebox then it does not push the content down. It just overlaps my content under it. Everything is in div's so not sure why this is happening.
Any idea?
Thanks
Karl, thanks so much for this technique. I'm very new to javascript, yet I was able to implement it from your tutorial. The only problem I'm having is that just at the very end of the smooth dropdown effect, there's a jerk as it finishes. I wonder if you could take a look at my implementation and tell me why you think that might be occurring. (Find the "See more" link in the first bio. You'll have to put that link up near the top edge of your screen in order to see the "snapping" effect at the bottom of the long slickbox div as it finishes opening.)
And while you're there, after you've opened the slickbox, please scroll down to the bottom of the page where you'll see that the background color of the left column ends before the bottom of the page. With the slickbox closed, that column "bottoms out" with the rest of the page, thanks to maxheight.js. But maxheight.js apparently gets the height of the tallest column when the page first loads, which means that if the page length increases after loading, which it does when visitors click the slickbox link, the left column is then too short. I researched ways to make the maxheight script trigger when slickbox is triggered, but my knowledge of javascript is too sketchy. I would need to know the precise code, and where to put it. Can you help? Thanks again.
The div that you're sliding up and down should have span-15 as one of its classes, not span=15. Fixing that will give the div a width, and that will help make the animation smoother.
Any thoughts on how to add a timeout to this using the setTimeout()?
Great tutorial! The cool (but relatively simple) things one is able to do with Jquery continue to amaze.
I have one problem though, i'm trying to bind the .toggle to multiple buttons, but if I have two buttons with the "toggle" class assigned to them, only one of them works. Do I have to differentiate somehow?
I have a problem when using this Hide show on radio group button.
I have two radio button "YES" and "NO"
I want to show on clicking YES and hide on NO
Both works. But the problem is Radio button is not checked. only the one select first remains checked always.
Thanks in advance for help
Karl
I spent hours to look for some tutorial that would find me something like yours ...
BOY o BOY ... where have you been hiding or was it just that huge tomato on my left eye. This is absolutely the best tutorial jQuery site I'd ever come across!
YOUR SITE IS BOOKMARKED on my side, that's for sure!
You have a new fan, Karl ;-)
and a
HUGE TAHNK YOU
Been working on this and it's working great, so thanks for that. My problem now is I have a row of buttons at about 80px high and then the hidden div slides underneath it and unless I click the same one again, the next one clicked will show underneath it.
Is there a way to show just one div at a time so when one is open and another is clicked, the one that WAS open closes and the new one opens? Also is there a piece of code I can use to add a .active class to the current a element?
Hello!
Thank you very much for a brilliant tutorial. I have an issue with the functionality. I have created an external JS file and linked it to my HTML. I have used ID's for the DIV's that I want to show/hide (there are few of them on one page) I have used ID's on my links as you can see. In theory everything should work perfectly. My problem is that on click of the link the browser instead of show/hide DIV, just jumps to the top of the page. Could you explain why?
The page can be previewed at: http://www.londonbrunel.com
Thank you very much,
Adam
Ok, I have managed to do it but there is funny effect if there is lot of content in the div. Even if I change the effects to .slideUp() it still does show the same effect as in the beginning. That is one of my worries. Another one is that my version of that code works properly on the Opera only, does not work on IE8+, Firefox 4 and Chrome. Do you know what could be the reason for that?
Thanks,
Adam
Page with the functionality described:
http://londonbrunel.com
Sorry, for bothering anyone. It was not the issue with my code the issue was with the host and the .htaccess file as I used the index.php file instead of the index.html that was not updated properly. So the code works now. Thank you very much for the great code that adds something more sophisticating to my website.
Adam
When hiding and showing multiple divs, what would cause the toggle effect to hide all of the divs at first load of the page (correctly) but after showing them, then rehiding them, it doesn't rehide them all. In this case, my bottom div. The divs and form inputs within my bottom div are not rehiding unless I give them all separate ids or classes. I don't wish to do that for styling and form data retrieval purposes, plus the div jerks badly that way when it is shown or hidden.
I am dynamically populating with PHP both the IDs in the javascript and the IDs of the divs, but the same problem occurred before I set it up that way. PLEASE HELP! Here's the gist of the code (the way that doesn't work: without the interior divs given their own ids and classes):
JS:
HTML/PHP of the DIV that won't hide.
If it is absolutely necessary to take out all of the PHP to get a response, let me know and I will. Really need to solve this for a huge project/client!
When hiding and showing multiple divs, what would cause the toggle effect to hide all of the divs at first load of the page (correctly) but after showing them, then rehiding them, it doesn't rehide them all. In this case, my bottom div. The divs and form inputs within my bottom div are not rehiding unless I give them all separate ids or classes. I don't wish to do that for styling and form data retrieval purposes, plus the div jerks badly that way when it is shown or hidden.
I am dynamically populating with PHP but it appears that code won't post here, so I've taken it all out. The problem remains. Here's the important parts of the code:
JS:
HTML:
Really need to solve this for a huge project/client! Thank you in advance!
Still trying to make this work with a checkbox. Using the checkbox as the trigger works fine except the checkbox doesn't actually check for some reason...
Any idea how to fix this?
I am trying to use this code on multiple divs... i.e. How do i get the JavaScript to hide div1 when i click on div2 , then hide div2 when i click on div3?
How would I add focus to the div when shown (for accessibility)
I am working on a new website and looking to replicate the effect of the pages here where a 'half' opaque slider overlaps the image, and has a scroll function enabled, embedded links etc.
http://www.pelicanhill.com
Just hit the menu buttons to see the functionality.
Is there coding or plugin that will create these effects in JQwery or ?
Thanks!
I think you should have provided the download option too :(
What do you mean by "the download option"? I provided a link to the script: http://www.learningjquery.com/js/slicker.js
I am trying to show a div and hide multiple, then click on other link to show one of the hidden divs and hide all others. My links are on left and divs on right. Toggle is OK for just 2 dives but I have 20 - show 1 hide 19, etc.
What is the modification to code for this?
Trying this now! Much better then what I was using before. Thanks.