Slicker Show and Hide
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:
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 "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.
-
// hides the slickbox as soon as the DOM is ready
-
// (a little sooner than page load)
-
-
// 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
UPDATE
If this type of showing and hiding isn't exactly what you're looking for, please check out my other entries and Jörn Zaefferer's accordion menu plugin:



September 24th, 2006 at 4:21 am
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?
September 24th, 2006 at 9:55 am
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!
November 9th, 2006 at 1:05 am
Hi,
is it possible to tpggle/slide/etc. all elements with the id of slickbox
ie.
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?
Cheers
Justin
justin@kelly.org.au
November 9th, 2006 at 9:39 am
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.
December 24th, 2006 at 7:20 am
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.
December 29th, 2006 at 3:44 pm
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.
January 22nd, 2007 at 8:19 pm
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!
HTML:
here is my link.js file:
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,
Don
January 22nd, 2007 at 11:40 pm
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.hideusinstead, 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:January 23rd, 2007 at 11:00 am
Karl,
That's got it! Thanks for your help.
Don
January 24th, 2007 at 4:29 pm
Hello i'm very new to jquery.
How is the slidedown-toggle effect achieved?
January 24th, 2007 at 4:32 pm
Nevermind, i think i'm becoming blind
January 30th, 2007 at 2:42 pm
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>
January 31st, 2007 at 8:16 am
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.
January 31st, 2007 at 9:53 am
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.
February 6th, 2007 at 10:39 am
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;
}
</cfloop>
and then in my javascript:
<cfloop from="1" to="3" index="i">
$('##slickbox_#i#').hide();
$('a##slick_#i#-slidetoggle').click(function() {
$('##slickbox_#i#').slideToggle(200);
return false;
});
</cfloop>
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?
February 27th, 2007 at 10:33 pm
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.
February 27th, 2007 at 11:36 pm
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":
Hope that helps.
March 5th, 2007 at 8:30 am
[...] Slicker Show and Hide [...]
March 17th, 2007 at 8:05 pm
Hi,
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.
April 7th, 2007 at 4:15 pm
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:absolutein your style sheet for the element to be shown and hidden and set its containing element toposition:relative.April 19th, 2007 at 8:30 pm
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
April 20th, 2007 at 10:50 am
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!!
-M
April 20th, 2007 at 11:08 am
@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.
@Matt,
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).
Cheers!
May 7th, 2007 at 11:23 am
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">
<tr>
<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>
<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>
</td>
</tr>
</table>
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!!!
Aaron
May 7th, 2007 at 7:53 pm
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
headMay 29th, 2007 at 2:02 am
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
May 29th, 2007 at 8:59 am
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
actionattribute 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.May 29th, 2007 at 12:33 pm
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</a>If you have an example and can lead me to a solution, that would be awesome!
Thanks again!
QT
May 31st, 2007 at 11:41 am
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!
QT
May 31st, 2007 at 7:06 pm
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.
June 17th, 2007 at 1:03 am
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!
June 21st, 2007 at 1:11 pm
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 expandeddiv, 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?June 25th, 2007 at 8:41 am
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.
HELP!?!
June 25th, 2007 at 8:50 am
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.
HELP!?!
June 25th, 2007 at 4:15 pm
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.
June 26th, 2007 at 9:06 am
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?
June 26th, 2007 at 9:46 am
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.
June 28th, 2007 at 10:50 am
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!
July 7th, 2007 at 12:10 pm
Nice tutorial.. works smoothly..
July 15th, 2007 at 12:17 pm
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.
July 15th, 2007 at 11:37 pm
Hi Dan, you should be able to accomplish this by using the
thiskeyword 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.July 16th, 2007 at 5:02 pm
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
And the jQuery code i'm using, which I took the majority of from your example:
July 25th, 2007 at 3:46 am
I can't get it working... =( I have this in the <head>
Then for my HTML I have
July 26th, 2007 at 5:27 am
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: http://pynx.org/~bostjan/pillbox/
Thank you in advance.
July 26th, 2007 at 7:38 am
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.
August 2nd, 2007 at 3:51 pm
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?
August 2nd, 2007 at 4:04 pm
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?
August 23rd, 2007 at 5:19 pm
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: http://www.kinow.org/book/toggleboxsample.htm. 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
August 23rd, 2007 at 5:32 pm
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-1.1.3.1.js"></script>it should be this:
<script type="text/javascript" src="/jquery/jquery-1.1.3.1.js"></script>August 23rd, 2007 at 7:45 pm
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
August 27th, 2007 at 8:54 am
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 (){
$("#testTable").find("a").click(function(event){
 $("#testTable").slideUp(3000)
})
})
Thanks in advance
August 28th, 2007 at 10:13 am
'Lambda function' comes from Lisp and the lambda calculus. Ask wikipedia for the details.
August 31st, 2007 at 4:54 am
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...
/index.html/#test5It 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/#test5would take you to the index.html page, scroll down to the #test5 id and slide open the next div.Thanks in advance.
September 13th, 2007 at 10:07 pm
How about this demo page:
http://jquery.com/files/demo/dl-done.html
From:
http://jquery.com/blog/2006/11/14/expandable-sidebar-menu-screencast/
JQuery:
$(document).ready(function(){
$("dd:not(:first)").hide();
$("dt a").click(function(){
$("dd:visible").slideUp("slow");
$(this).parent().next().slideDown("slow");
return false;
});
});
He used dl, dd & dt to format the HTML code.
September 14th, 2007 at 11:33 am
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:
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.
September 25th, 2007 at 4:22 pm
Karl,
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 (elem.style has no properties)
Hope this helps - keep up your excellent work!
September 25th, 2007 at 8:52 pm
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!
September 26th, 2007 at 5:08 pm
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.
October 16th, 2007 at 11:01 pm
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?
Thanks!
$(document).ready(function() {$('.form_email').hide();
$('a.toggle_email',this).click(function() {
$('.form_email').toggle(400);
return false;
});
});
October 16th, 2007 at 11:11 pm
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:
October 17th, 2007 at 7:31 pm
Awesome! That did the trick thanks!
October 21st, 2007 at 8:04 am
I like jQuery !
and so Thanks Thanks and Thanks for this learning guy !
October 23rd, 2007 at 6:50 pm
Hi,
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)
$('#adminNav').show();
// toggles the box on clicking the noted link
$('a#toggleAdminNav').click(function() {
$('#adminNav').toggle();
return false;
});
});
some link
some link
some content
October 25th, 2007 at 2:51 pm
Hi there,
Great stuff, just one thing..how do I load dynamic (external) content, say something.html into the displayed DIV?
Any help greatly appreciated.
Many thanks,
Nim
November 2nd, 2007 at 9:43 am
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 "element.style display:table" There are three tables being toggled on the page, so I want to specify only the table associated with the clicked element.
Code:
$("#nutritionBar").click(function () {
$("#nutrition").toggle();
if($("#nutrition").attr("display")=="hidden"){
alert("hidden");
$("#nutritionBar a").text("Expand Nutrition Planner");
}
if($("#nutrition").attr("display")=="table"){
alert("table");
$("#nutritionBar a").text("Collapse Nutrition Planner");
}
});
--->
November 2nd, 2007 at 11:16 am
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):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.
November 2nd, 2007 at 11:18 am
One more thing, make sure that all of the above code is wrapped inside a "document ready":
November 2nd, 2007 at 11:38 am
Thanks, Karl! That should give me something to work with. I left out the "ready" as assumed...post-submit I wondered if it would cause confusion...
November 5th, 2007 at 8:24 am
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?
November 5th, 2007 at 9:55 am
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?
November 8th, 2007 at 10:13 pm
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!
November 15th, 2007 at 4:58 am
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
November 20th, 2007 at 10:21 pm
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.
November 27th, 2007 at 4:43 am
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
Moshfiq
November 27th, 2007 at 11:03 am
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."
December 4th, 2007 at 7:59 am
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
December 7th, 2007 at 11:16 am
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?
December 15th, 2007 at 10:59 pm
Karl,
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)
December 15th, 2007 at 11:47 pm
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:
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()
December 17th, 2007 at 12:18 pm
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.
Lance
December 17th, 2007 at 12:36 pm
let me explain a bit more. I would like this in the document when first loaded:
December 26th, 2007 at 6:11 pm
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
December 26th, 2007 at 6:21 pm
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<and>.Thanks.
December 27th, 2007 at 4:16 pm
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?Thanx
December 27th, 2007 at 6:22 pm
Karl,
Do you have any examples where tabs are populated by RSS feeds?
Lance
December 27th, 2007 at 7:12 pm
Karl,
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)
December 28th, 2007 at 1:33 pm
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
K
December 28th, 2007 at 5:15 pm
@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.
December 29th, 2007 at 3:22 pm
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
K
December 31st, 2007 at 5:16 am
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 http://www.ellenseyes.com if you'd like to take a look how I achieved it.
I'll look for your post.
Happy New Year!
December 31st, 2007 at 9:15 pm
Karl,
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 http://ellenseyes.com/testpages/MoreLessSummary.php
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.
January 4th, 2008 at 11:35 am
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:
It doesn't work. Firefox says "Error: $ is not a function". What am I overlooking?
January 4th, 2008 at 11:45 am
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.
January 4th, 2008 at 1:23 pm
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...
January 29th, 2008 at 2:55 pm
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.
March 4th, 2008 at 3:37 pm
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:
And this is what I have in the body:
The second paragraph is hidden but won't show upon clicking the link. Can you help?
March 4th, 2008 at 10:53 pm
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.
March 13th, 2008 at 3:19 am
How about toggle of the text?
March 20th, 2008 at 6:20 am
I have this code in place:
and want toogle this HTML code:
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?
March 20th, 2008 at 10:38 am
Hi philk,
Try this:
April 1st, 2008 at 5:18 am
How do I use this 'show' 'hide' for dynamic content ?
I may have numerous
April 1st, 2008 at 8:45 am
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.
April 2nd, 2008 at 8:09 am
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.
April 2nd, 2008 at 8:46 am
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.
April 11th, 2008 at 6:13 am
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:
And if there's any way i could insert bullet into the subcontent?
Thanks!
April 11th, 2008 at 12:06 pm
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.
May 1st, 2008 at 8:56 am
thanked post
May 1st, 2008 at 9:01 am
thankssss
May 9th, 2008 at 4:03 am
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?
May 9th, 2008 at 8:27 am
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.May 15th, 2008 at 3:55 pm
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:
And the html includes:
What am I doing wrong? Thanks!
May 15th, 2008 at 4:10 pm
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?
May 15th, 2008 at 4:39 pm
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!
May 15th, 2008 at 4:42 pm
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.
May 16th, 2008 at 5:41 am
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!