Jquery: show/hide multiple elements independently
Hiding a single element with Jquery was pretty straightforward. But what about if you want to show/hide multiple elements independently?
Thanks to Justin Young for requesting this new function and getting me to do something useful ;)
As before, the aim was to make portable, accessible code. All that's needed for the script to work is to give any element (an entire div, a paragraph, whatever) a CSS class of "toggle". The preceding element (i.e. the element directly above the thing with a class of toggle) will have a show/hide link added to it. This seemed like a good approach, and works especially well with sections marked up with headings.
Update: 23/1//09 - thanks to Juraj in the comments below who came up with a solution for using HTML in the show/hide links
The code
// Andy Langton's show/hide/mini-accordion - updated 23/11/2009
// Latest version @ http://andylangton.co.uk/jquery-show-hide
// this tells jquery to run the function below once the DOM is ready
$(document).ready(function() {
// choose text for the show/hide link - can contain HTML (e.g. an image)
var showText='Show';
var hideText='Hide';
// initialise the visibility check
var is_visible = false;
// append show/hide links to the element directly preceding the element with a class of "toggle"
$('.toggle').prev().append(' (<a href="#" class="toggleLink">'+showText+'</a>)');
// hide all of the elements with a class of 'toggle'
$('.toggle').hide();
// capture clicks on the toggle links
$('a.toggleLink').click(function() {
// switch visibility
is_visible = !is_visible;
// change the link depending on whether the element is shown or hidden
$(this).html( (!is_visible) ? showText : hideText);
// toggle the display - uncomment the next line for a basic "accordion" style
//$('.toggle').hide();$('a.toggleLink').html(showText);
$(this).parent().next('.toggle').toggle('slow');
// return false so any link destination is not followed
return false;
});
});
Multiple show/hide in action
Section one: a div with a paragraph
You can show/hide an entire div by giving it a class of "toggle". Links and other child elements will work fine too. The element directly before this one is a heading, so it gets a show/hide link appended.
Section two: single paragraph
A single paragraph can be hidden by giving it a class of toggle too. I can't help but be impressed by how easy it is to use jquery - even for someone with limited programming and javascript experience like me. Again, the preceding element is a heading.
Now: a list
- You can even hide a list
- Just give the <ul> the toggle class
- This time the preceding element is a paragraph
13.10.2008. 18:52
Andy said on 24.11.2008. 16:27
This may be a silly question but I'm new to Jquery and couldn't get it to work which got me wondering,..... is this a .php specific script (I'm just wondering as it's got the $ on each line). It doesn't seem to say in the article.
If it is, doesn anyone know of a similar solution for .asp as this one is really nice and clean.
Thx
Andy said on 24.11.2008. 16:30
It's pure javascript, but is based around the jquery library, so will run on any html page (including PHP and ASP-generated pages). Probably it didn't work because you didn't link to the jquery library itself. I'd suggest you start with "getting started" in the jquery docs:
http://docs.jquery.com/Main_Page
Ron McElfresh said on 24.11.2008. 19:37
I notice that the code above does not validate XHTML 1.0 transitional (using BBEdit) because of the
Andy said on 25.11.2008. 11:35
Hi Ron,
Apologies - I think the HTML you included got stripped (I'll look into sanitising that as opposed to ditching it entirely).
Generally, I include all javascript from external files, which means there can't be any validation problems. If the reason it doesn't validate is due to the HTML for a link included, you can split this up within the code so the validator doesn't confuse it for a link, or put comments around the whole script block. But I always favour external files for js which is IMO much cleaner.
MojoWill said on 25.11.2008. 21:04
Great script just what I was looking for is there anyway to make an entire line f text the toggler? or style the show/hide text somehow?
Im using it for a FAQ clickin to show the answers
http://testing.mostlymojo.com/hertford/faq.php
Andy said on 26.11.2008. 10:09
You can easily style the toggle link - it has a CSS class of "togglelink".
To make the entire text a link, you can use the jquery "wrap" method:
http://docs.jquery.com/Manipulation/wrap#html
I.e. change the line
$(".toggle").prev().append('(<a href="#" class="toggleLink">'+showText+'</a>)');
to
$(".toggle").prev().wrap('<a href="#" class="toggleLink"></a>');
I haven't tested this, but should work in theory.
Andy said on 26.11.2008. 10:13
@test - what problem occurred? Did you get a javascript error? Are you using external js? It worked fine for me in IE when I tried it.
Tony said on 02.12.2008. 14:06
Hi there. This is an excellent script. Very like an Ajax Accordion that I was looking for, but using JS.
However, is it possible to modify the script so that the previous text is hidden when the next one is shown, more like the way an accordion works?
aguspuryanto said on 03.12.2008. 08:11
i want to replace text "Show" and "Hide" on the script with image. do you have solution?
// choose text for the show/hide link
var showText="Show";
var hideText="Hide";
Replace with:
var showText='';
var hideText='';
Jake Rutter said on 06.01.2009. 16:31
Nice work, your code was helpful in helping me with a script that I was creating.
Lee Amador said on 16.01.2009. 17:12
How can I change the toggle effect to something like slideUp/slideDown? Thanks in advance.
Andy said on 19.01.2009. 15:12
SlideUp/slideDown is straightforward enough, but requires a little modification. First, omit the current toggle display line, then change the show/hide text lines to the below:
// change the link text depending on whether the element is shown or hidden
if ($(this).text()==showText) {
$(this).text(hideText);
$(this).parent().next('.toggle').slideDown('slow');
}
else {
$(this).text(showText);
$(this).parent().next('.toggle').slideUp('slow');
}
Mahzian said on 10.02.2009. 06:18
brilliant, just what I was after (and more, I thought I needed a bunch of different id's and individual click functions)
Thanks muchly!
hi, i am traying show/hide difrent images (png). Only i get mess..
var hideText=';
var showText=';
garr, garr
// this tells jquery to run the function below once the DOM is ready
$(document).ready(function() {
// choose text for the show/hide link
var showText='';
var hideText='';
// append show/hide links to the element directly preceding the element with a class of "toggle"
$(".toggle").prev().append(''+showText+'');
// hide all of the elements with a class of 'toggle'
$('.toggle').hide();
// capture clicks on the toggle links
$('a.togglelink').click(function() {
// change the link text depending on whether the element is shown or hidden
if ($(this).html()==hideText) {
$(this).html(showText);
}
else {
$(this).html(hideText);
}
// toggle the display
$(this).parent().next('.toggle').toggle('slow');
// return false so any link destination is not followed
return false;
});
});
Image change only one time :( when hide element, correct image didint showed :(
Andy said on 13.02.2009. 15:52
I fixed the problem, ca - if you use the code in the post it should now work. What changed was using this.html instead of this.text (text sanitises HTML)
I've been trying to modify your code to hide 3 divs and show 1, which divs depending on which of the 4 links are clicked, but I'm having no luck.
Is it possible to do this code or is it tricky to do an operation such as the above?
Andy Langton said on 17.02.2009. 22:56
If you want this to work "accordion" style (i.e. only one of the toggle elements is displayed at a time) then you just need to hide all of the toggle element prior to display.
Add the following directly underneath the comment // toggle the display
$('.toggle').hide();
Instant accordion :)
john said on 06.03.2009. 16:20
Hi Andy,
what a great set of functions -- thanks a lot for your phantastic work!
The only thing that doesn't work for me is your accordion suggestion (17.02.2009,2:56):
The accordion unfolds as expected, but if I click on 'hide', the text doesn't hide but the toggle text just changes to 'show'...
Would be great if you could provide some help.
Thanks again!
KatieB said on 09.03.2009. 01:09
Just a quick note on W3C validating xHTML inline scripts that use characters such as $ and &, if you wrap the content of the script with <!//ript stuff here //]]> it will validate properly.
John said on 11.03.2009. 20:33
Hi Andy and all,
seems my above question wasn't clear enough, so I'll try again -- the accordion suggestion (17.02.2009, 2:56) has a little flaw: If I apply the accordion suggestion with the three example sections above, the accordion just works once (i.e., when clicking on the "show" link of a section, the previous section is getting closed). After that, all three sections have the toggle text "hide", although, after being clicked, the respective toggle link should read "show", not "hide". Get what I mean? Any suggestios on how to solve this?
Cheers, John
Andy said on 11.03.2009. 22:08
Hi John,
Thanks for spotting this. I've adjusted the code in the original post to rectify this problem. The solution is a bit hackish, but is as a result of the original implementation which checked the text of the show/hide link. Give it a go and let me know if it works for you :)
Andy
John said on 12.03.2009. 16:35
Thanks a lot for your efforts, Andy!
I'll get back later tonight with a few comments.
John
Andy, this script is exactly what I have been looking for. I am having a problem using images as the toggle links, however. Everything works great until clicking the "hide" image. The elements toggle correctly, but the original "show" image does not return ("hide" image persists). I think this is the same issue CA had. Am I doing something wrong? Thanks.
Andy said on 18.03.2009. 14:22
To those with problems using images etc. in the show/hide text, I think i figured out the problem. When return the value for the HTML of an element, jquery seems to change single quotes to double quotes - so the solution is for the showText and hideText variables to be contained within single quotes, and any attributes of elements within to be enclosed in double quotes. Who knew?
Andy, thanks for the response. I figured out the single/double quotes issue already, but the script still does not ever re-load the initial image. Everything works correctly, but the "hide" image persists forever. Have you had success with show/hide images?
Aaron said on 19.03.2009. 02:04
Is there a way to have two links for two different hidden divisions, and when you open one, then the other, the first one closes when you open the second one?
Andy said on 19.03.2009. 09:31
@Dan - is this with internet explorer? After a bit of testing, it looks like IE does not return the same value for the inner HTML of element after it's created (it uppercases the tag name for one thing ). I've not figured out how to get around this behaviour yet. I have it working fine in Firefox/Opera with the code above.
@Aaron - it sounds like you mean an "accordion" effect - uncomment the relevant line in the original code and see if that works out for you.
Hi Andy - Yes, the issue only occurs in Internet Explorer. I'd love it if there was a way around this IE bug!
Andy said on 25.03.2009. 11:26
Actually after some research, it looks like it isn't an IE bug necessarily (it also affects Opera). It seems to be related to the value of innerHTML in certain browsers (see http://andylangton.co.uk/tmp/jquery-html.htm ), but I haven't pinned down a solution yet.
Rocky Patel said on 27.03.2009. 11:31
Hi All,
Just an FYI - I'm new to jQuery.
I want to use the above code for in one of the sections on our Agenda page (http://www.pershing.com/events/insite/agenda/index.html). If you scroll down to 2:30 p.m. - 5:00 p.m. on Wednesday June 3 you'll see "view/hide details" link. I have no issues hiding this single element but what I want is once a user clicks on "View Agenda" it will expand out and on the bottom you'll see a "hide" link. Once the user clicks on "hide" the element will slide up and the text should read "View Agenda". So I guess I need some "onclick" functionality for the "hide" functionality on the bottom. Can somebody please assist. I hope I explained this correctly. Thanks.
Interesting find about Opera, Andy. I know I've seen this effect in other jquery scripts but I'm not experienced enough to offer any help, unfortunately. I'll keep hoping for a solution.
Harsimran Kaur said on 02.04.2009. 06:20
Hi,
Can you help me making the whole text line under or tag making a link so that if I click the whole line it shows and hides the .toggle class content. That simply means that I don't want to use the show/hide text preceding .toggle class.
Benjamin Thomas said on 21.04.2009. 07:48
I would like to use this script, however I don`t want the show/hide link to be created via javascript, since this not accessible. My show/hide link is in the HTML instead, marked with a class. Also my toggled content is marked with a class.
Let`s say I have this setup:
Show/Hide Content
Some content here
How does my script need to look like???
I am always confused with the referencing ("this"). and parent/child..
Many thanks for your advice!
Andy said on 21.04.2009. 10:18
>> I don`t want the show/hide link to be created via javascript, since this not accessible
If the functionality requires javascript (which it does) then writing show/hide links in anything other than javascript is inaccessible, since it means users will see a link that cannot possible function.
If you must hard-code inaccessible links, then you just need to give them a class of "togglelink".
Sunil K said on 22.04.2009. 12:22
This is really great...I am using this script to navigate certain links and is overlaping a form. but when i try this div ie 6 it doesn't overlaps the select box ...any solution for that?
Hi,
To start with I would like to thank author for this script, it is great :)
I think I sorted out the problem with image, which was getting stuck.
The problem is that every browser represents and modifies html code differently.
$(this).html ($(this).html()==hideText ? showText : hideText);
When I tried to look what exactly is inside variables $(this).html() and hideText when comparing, it was different in every browser...
Explorer uses uppercase for tag IMG, Mozzila uses lowercase...
So, I just edited the comparasion line that every string is lowercase:
$(this).html ($(this).html().toLowerCase()==hideText.toLowerCase() ? showText : hideText);
I hope it helped.
Greg said on 26.05.2009. 11:18
Hi Andy
How could I get the hide link to be at the end of the revealed element?
I'm toggling a long piece of text and it would be useful to be able to hide it from a link at the end.
Hope this makes sense.
Hi. Great script!
How can I modify it to give also the possibility to show all hidden text at once with a "Show All" link? and to hide everything again?
I mean is it possible to have both independent and simultaneous show/hide in the same page?
Thanks in advance and again great script!
Andy said on 28.05.2009. 19:23
>> How could I get the hide link to be at the end of the revealed element?
At the moment, the link is appended to the previous element:
$('.toggle').prev().append();
It sounds like you want to append it to the current element:
$('.toggle').this().append();
>> is it possible to have both independent and simultaneous show/hide in the same page
Yes! You just need a link which toggles *every* element with a class of toggle:
$('.toggle').toggle('slow');
Jefte Puente said on 05.06.2009. 17:23
Thank you Andy! I was tearing my hair out having to write individual bits.
AU said on 06.06.2009. 21:46
Andy - thanks so much for this!
For my website, I needed the whole text to be the link, so I've adjusted your code to do this. You can then set CSS styles to the text.
/*---
Here's your text!
--*/
kampie said on 18.06.2009. 22:12
Great script Andy, thanks!
If I would want to show/hide a div element that is not immediately following the link, would that be possible?
James said on 03.07.2009. 16:59
Hi Andy,
Great script, I've already found a couple of uses for it but on one site, I'm stuggling to get it to simply wrap the link around the preceding paragraph and changing the line you mention in about the 3rd comment doesn't work properly.
Any ideas how I would simply make each question here http://tinyurl.com/m55atn into a link rather than having the show/hide text?
Cheers!
James.
Money Off Shop said on 13.07.2009. 00:19
Hi Andy - great piece of code :) Thanks for a nice hide/show jquery example - easy to understand and follow :) I'm interested to know though if it would you be possible also open a new browser window at the same time as the element is revealed by clicking on ‘Show/Hide’ action please?
Xavier Riley said on 15.07.2009. 08:25
Hi Andy,
This script is mega, just what I needed but I can't get it to work properly with images instead of text.
The images themselves display just fine, but when I click 'hide' the graphic doesn't change. I think its something to do with the logic checking for innerHtml (ie some text) for an image? In the line following this comment "// change the link depending on whether the element is shown or hidden". Any ideas? Thanks again for a really useful script.
Xavier Riley said on 15.07.2009. 10:48
Ok I solved my own problem with it but it'll be tricky to demonstrate without being able to type html :P
If using an img instead of text for the showText and hideText variables, make sure they don't have a / before the last bracket, as jQuery strips this making the variable different from the innerHTML. This means it always shows the 'hide' img after being clicked for the first time.
To see what i mean, use an img with a self closing tag (ending '/>' ) then put alert($(this).html()); in the function and see the difference.
John said on 22.07.2009. 13:09
I'm having the same problem as Xavier: when I first click the link ("Show +", where the + is an image), it changes to "Hide -", but then will not change back if I click again.
The accordion still works, but the hideText link fails to change. I only find this issue in Internet Explorer 8 (it well could be in older versions). Firefox works perfectly.
One bug I found with Safari is that when the element with the class "toggle" is animating into view, it pushes my page layout horizontally, making the horizontal scroll bar appear for a few milliseconds.
Still, this is an awesome script that is much easier to use and much more accessible than others I've seen.
Greg Malkin said on 27.07.2009. 16:53
Great job on the script! :-)
Could you please help me with something? How can I insert the show/hide links somewhere other than just before the 'toggle' div?
I'm integrating this into a table to show/hide a table row and as it is, the links are being added into the preceding row () whereas I need them added into the cell () before the following closing tag ()
Any ideas on how I could do this? If you can help i'd be very grateful. My email is greg@dekken.co.uk.
thanks,
Greg.
Andy said on 04.08.2009. 18:47
For those with problems using html for the show/hide links, take a look at http://andylangton.co.uk/tmp/jquery-html
What's happening is different browser return different values for html(). I didn't see any easy solution to this, but the options I looked at were:
- "Normalising" the output from html() (seems tricky when IE re-orders attributes in the img element!)
- Using a different check for visibility (is_visible or something similar?)
If anyone gets either of the above working, I'd love to see the code :)
madhu said on 14.08.2009. 08:54
Hi,
jQuery
google
i need alert message for both the links diggerent can u pls.
thank you
Lothar Velling said on 14.08.2009. 18:09
Thank you very much. Still fiddling a bit with the CSS alignment, but some work has to be left, doesn't it?
Basilakis said on 21.08.2009. 17:01
Excelent script, but neither a download link, not a good way to pass that in a web site.
Needs more documentation...
Ferry Helmich said on 24.08.2009. 11:21
Hi,
There seems to be a bug with margins in Internet Explorer when the "Hide" button is pressed. Does anybody know how to solve this problem?
You can see it here: http://www.plazaitalia.nl/bestellen
I hope somebody can help me out!
bytor said on 01.09.2009. 07:54
Hi Andy I tryed to use image instead of text but it didnt work.. any help on this..
var showText="";
var hideText="";
jordan said on 02.09.2009. 13:51
Great script, Andy. Thanks for putting it together. I'd like to use it in a situation where the element preceding the div to be hidden is a link, but this method of appending the hide/show link to the previous element seems to cause the hide/show link to activate the previous link as well when hovered. Does that make sense? When I hover the dynamically created "hide/show" link the "direct" link also appears hovered. My setup is like this:
link to go directly to the content
Description of the content
Thanks in advance for the help!
jordan said on 02.09.2009. 13:57
PS. It's early and I'm not using my words very well - what I'm looking for is to add the hide/show link AFTER the closing tag of the previous element, rather than placing the hide inside the preceding link.
Thanks again- J
Lu said on 10.09.2009. 05:45
Nice, thanks! How about taking showText and hideText from the HTML code? That would make the script more universal?
Victor said on 16.09.2009. 22:21
I'm seeking for a method to show or hide all toggle elements regardless of whether they are currently showing or hidden.
The trigger for this global hide/show would read "show all" or "Hide all" depending on status.
Am continuing Googling and experimenting and will post results if unearthed.
Juraj said on 19.09.2009. 22:34
Thanks to Andy's suggestion I managed to solve the whole image changing problem:
1. create a new variable:
var is_visible = false;
2. add the following right at the beginning of the click function:
is_visible = !is_visible;
3. change the condition which sets the text to the following:
$(this).html( (!is_visible) ? showText : hideText);
Brice said on 03.10.2009. 08:53
Sorry for the noob question...
But is there a way to use the "Show" and "Hide" on an existing image? I already have an image that, when clicked, will trip the jQuery and open the 'toggle' div. How would I do that?
Thanks!
Sorry to be posting what I imagine to be a fairly basic question. I'm having a problem with multiple instances of the show/hide link being created.
I'm using the following script to autoload content in the style of the Facebook wall:
http://9lessons.blogspot.com/2009/07/load-data-while-scroll-with-jquery-php.html
The problem is that each time the script fires to add new content, each previous show/hide anchor has another one added to it, with only the final itteration of it working correctly.
How can the script be modified to avoid this - presumably detecting where the togglelink class has already been appended.
Many thanks - this is a really useful script.
Ben
Andy Langton said on 05.11.2009. 17:47
Ben, it sounds like you may have a problem that would be solved by the Jquery "live" event:
http://docs.jquery.com/Events/live
Mark said on 26.11.2009. 11:36
Here's a video tutorial which I've just found on the web which eplains show/hide effect: http://www.sebastiansulinski.co.uk/web_design_tutorials/tutorial/52/show_and_hide_div_with_jquery
Colin said on 26.11.2009. 14:45
Hi
There seems to be a problem with the text in IE it looks different to the "unhidden" text, lighter and rather spider like. Ok in Firefox of course.
C
Ahsan R. Shami said on 30.11.2009. 01:05
I've read through the comments a few times and haven't found a way to make the preceding text a link, though the question's been asked a couple of times.
The WRAP suggestion didn't work, at least not what I copy/pasted.
In a nutshell, I'd like to keep the show/hide links that the code creates, but I also need the text that it's appended to changed in to a link.
Help?
The Googler said on 02.12.2009. 19:31
Hi,
Excellent script.
Is there a way open one of the divs with an incoming link? I want to reference it by id so I could have links like: http://www.myurl.com/test.php#12
It would open the toggle div that had the id of 12 and left the others closed.
Just wondering if this is possible, and if you could help me out, Thanks!
Ramesh said on 05.12.2009. 05:12
Amazing script!!! Thank you very much....
Disco said on 10.12.2009. 17:05
Hi, Thanks for this code it really adds something extra to a blog. I saw Tony's comment about only showing one div at a time which I know is pretty tough in blogger. I also wanted to acheive something similar where one div opens and the other one closes automatically. I have just about managed to do it and have used the javascript code (as untiday as it is) to create menus on my blog which open tabs. Have a look at my post about the Funk Band WAR on my blog http://disco.funk-atuneaday.blogspot.com for an example. I challenge anyone to try and tidy up the code a bit so that it still works on blogger. Perhaps you might want to do a post on this cript Andy?
Mark said on 23.12.2009. 18:54
Thanks for this script Andy - definitely what I was looking for. I do seem to see one little issue that no one else has commented on:
When the page loads in IE (IE 7 at least), the divs are briefly shown -- they disappear after the page completes its load.
Do you know of any way to hide these earlier so user don't see the text initially?
Behavior is consistent both on my test version of your script and on this page itself.
Thanks!
Elias said on 23.12.2009. 21:03
Hey there,
Great script!
I'm finding that the "show" link doesn't change over to the "hide" link after clicking.
I have set it up to work accordian-style if that's relevant.
Any ideas?
morvi said on 10.01.2010. 23:46
Great tool!
I am a newby - my first jquery thing - and still manage to
a) included am image
var showText=' ';
b) Show All and Hide All
$(document).ready(function(){
$('a.hideAll').click(function() {
$('.toggle').hide();
});
$('a.showAll').click(function() {
$('.toggle').show();
});
});
and the html ...
Show all | Hide all
NOTE: is not perfect - the [+] and [-] gets mixed up - but I use the same image for both - so I'm happy ;-).
Tracy Chamblee said on 16.01.2010. 16:04
Perhaps I overlooked something here, but it would be nice if it were clearly (& noticeably) spelled out that:
"The code" above needs to be placed in the body tag to work.
Also a direct link to jQuery pack 1-2-3 would have been nice to mention. The direct link:
http://jqueryjs.googlecode.com/files/jquery-1.2.3.pack.js
The page with all the jQuery 1-2-3 files:
http://code.google.com/p/jqueryjs/downloads/list?can=1&q=jQuery-1.2.3
Hope this helps someone, as these were the two dilemmas I ran into myself.
Works like a charm now, absolutely beautifully!
Many Thanks! :)
Tracy
Tracy Chamblee said on 16.01.2010. 19:04
I have noticed that the script displayed on this page (http://andylangton.co.uk/articles/javascript/jquery-show-hide-multiple-elements/), is different compared to the script you are actually referencing that's in the source.
The script Copied From the Page is glitchy. Sometimes the text 'show' does not swap to the text 'hide'. And sometimes if it does, it does not swap back. You can see it for yourself here:
http://www.flipflopmedia.com/test/TogglePage.html
Simply click to expand/contract each element back and forth to see the glitches for yourself and what I'm talking about.
The script Copied From the Source is here:
http://www.flipflopmedia.com/test/ToggleSource.html
Has no problems whatsoever.
Here's my problem. Trying to implement an image:
script in the example is Copied From the Source
http://www.flipflopmedia.com/test/ToggleIMG.html
I changed the following section (along with adding the image tags in ShowText/HideText)
// change the link depending on whether the element is shown or hidden
if ($(this).html()==hideText) {
$(this).html(showText);
}
else {
$(this).html(hideText);
}
IF I use the script Copied From the Page, I can get the image to swap back and forth, when it wants to; it's glitchy, as I said.
IF I use the script Copied from the Source (as it is right now on ToggleIMG.html, the image does not swap back to it's original "show" state.
This is just a test toggle image, not the one I would like to use.
I would also like to know how to make this image proceed the text, vs. append? I tried the 'wrap' suggestion and it did not work?
I'm about ready to give up on the whole idea and just use Show/Hide actual text at the end of the text!
Thanks,
Tracy
mac_major@mac.com
Meridyth said on 07.02.2010. 18:45
Thanks for this, spent ages trying to get something like this to work. very helpful post!
Your toggle resets my CSS formatting, specifically DIV padding.
Any way to get around this ?
John r hopkins said on 04.03.2010. 18:19
This is exactly what I've been looking for. Perfect.
However, I must be missing something. I'm using wordpress and thesis as a theme and something seems to prevent it from doing the show/hide bit.
Here is where I'm trying it. I've applied the toggle class to the unordered lists below Utah and Georgia.
And nothing seems to be working :( Any thoughts as to what I might be overlooking?
John r hopkins said on 05.03.2010. 00:22
I found the solution. Thought I'd share the solution. Since Wordpress 2.8 uses a modified jquery in order to avoid conflicts, all calls using "$(" need to be changed to "jQuery(".
I tried it and it works right away.
// Andy Langton's show/hide/mini-accordion - updated 23/11/2009
// Latest version @ http://andylangton.co.uk/jquery-show-hide
// this tells jquery to run the function below once the DOM is ready
jQuery(document).ready(function() {
// choose text for the show/hide link - can contain HTML (e.g. an image)
var showText='Show';
var hideText='Hide';
// initialise the visibility check
var is_visible = false;
// append show/hide links to the element directly preceding the element with a class of "toggle"
jQuery('.toggle').prev().append(' ('+showText+')');
// hide all of the elements with a class of 'toggle'
jQuery('.toggle').hide();
// capture clicks on the toggle links
jQuery('a.togglelink').click(function() {
// switch visibility
is_visible = !is_visible;
// change the link depending on whether the element is shown or hidden
jQuery(this).html( (!is_visible) ? showText : hideText);
// toggle the display - uncomment the next line for a basic "accordion" style
//jQuery('.toggle').hide();jQuery('a.togglelink').html(showText);
jQuery(this).parent().next('.toggle').toggle('slow');
// return false so any link destination is not followed
return false;
});
});
wanderingdays said on 07.03.2010. 20:48
Thanks for the instructions. I found a minor issue with the is_visable. Hard to describe, but the following fix should tell something.
Changing this:
$(this).html( (!is_visible) ? showText : hideText);
to this:
$(this).html( $(this).parent().next('.toggleSection').is(':visible') ? showText : hideText);
Gabriel Lora said on 14.03.2010. 19:21
Hi!
I am having problems with this script. The script is to some working to some point (because when I click the link, the word show/hide toggles), but the p.toggle is not showing/hiding...
Can anyone please help?\
(next to the 1st pic, where it says + info, that's the link above the p.toggle)
http://gabolora.com/stereoptico/artists.html
Vin Thomas said on 17.03.2010. 05:33
This is a great script. I find it very useful. But I am having issues on one page. If I toggle several of the divs on this page (http://wsfc.org/im-new/who-we-are/) I am getting some strange behavior. Sometimes it opens fine, but when I close it the toggle image gets reversed.
Any clues on how to solve this?
Jen S said on 22.03.2010. 08:20
Thanks a ton! This works like magic. I'm a long-time coder but new to jquery. I was trying to figure out how I was going to get each one of my post's comments to show and hide without making a million different functions. I'm still having some trouble with IE (The div starts to show, and then changes it's mind halfway through) but I think the answer is probably in the comments. I'll take a look. Thanks again!
Lori said on 22.03.2010. 17:13
These hide/show links are great. I did notice, however, that when I turn off CSS, the hidden text is shown, but the toggle link says "show". When I click it, the text hides and the link then says "hide". So basically when CSS is off, the links say the opposite of what they should. I'm trying to make this feature as usable/accessible as possible so any help would be great.
Alex said on 03.04.2010. 21:16
How can I have the first div be open on page load. Otherwise all DIVs are hidden. I would like the first one to be open when entering the page. Thanks.
whebz said on 16.04.2010. 09:25
is it possible to hide or show the div tag depends on a textbox value?
Steve said on 22.04.2010. 17:26
Hey Andy,
Great script, this is just what I was looking for.
I had a few issues, but it was nice to see that you actively respond to comments and provide "support".
I just wanted to mention that JAY's (14.05.2009. 21:34) suggestion fixed one of my problems. When using multiple Show/Hide (for synopses in a knowledge base) it would not toggle to the correct word. It seemed to track the last toggle overall rather than the setting for each link. In other words, if I clicked show on the first article, it would change to hide. If I pressed show on the next article without hiding the previous, it would stay at show, and if i try and hide the first article now, that word remained hide.
I guess this has been really wordy and maybe confusing, but all in all great simply script, it is much appreciated.
Marie Kyle said on 22.04.2010. 22:13
thank wanderingdays! the page i was working on (4evermarriages.wearehenrykyle.com/faq) kept having this weird issue. I have multiple show/hides going on, but everytime you clicked in a new 'show' link to reveal text, the word 'hide' would only update on every other click. Changing this:
$(this).html( (!is_visible) ? showText : hideText);
to this:
$(this).html( $(this).parent().next('.toggleSection').is(':visible') ? showText : hideText);
fixed the issue. thanks again!!
How can implement COOKIE, for remember state ?
This source is clean, i like! Thanks for advanced!
jay said on 28.04.2010. 07:28
Hey do you mind if I use some of this content on http://www.basicwebdesign.co.cc in exchange for a link back to your site? Thanks
Eric said on 05.05.2010. 18:14
Thank you for sharing this code! Exactly what I needed for a project I'm working on.
RickA said on 13.05.2010. 23:08
Andy,
Works nice unless I want more than one paragraph or and unordered list. Then it doesn't hide the part after the paragraph break. Is this an easy fix?
benjamin holland said on 21.05.2010. 00:55
another real easy way of doing this is ....
$(document).ready(function() {
$('#faq').find('dd').hide().end().find('dt').click(function() {
$(this).next().slideToggle();
});
});
question
answer here.
gabe said on 21.05.2010. 21:52
I have the same problem as Ben. I'm applying this great script to a search engine results page. If I get 4 results I get for instances of "show" with only the last one working properly. If i get 10 results I get 10 instances of "show" with only the last one working properly, etc.
I have read up on jquery .live() and do not see how it can solve this problem.
Thank you very much Andy.
Russ said on 25.05.2010. 20:58
@RickA I implemented the code in a content management system for a client. Ease of use is a must, so I settled on using a div container with the toggle class. All of the paragraphs and lists falls in properly without random "Show" links throughout.
Might not be perfect right away, but with some CSS, this method should work for your needs.
Ken said on 02.06.2010. 22:37
great script. Exactly what I was looking for. Thanks a bunch.
Michael said on 16.06.2010. 02:45
hey Andy, I really like what you have done here. very impressive. only thing I wanted to know is. how would you assign a cookie onto to your js so if I was to click away from this page and then back again the page would remember the selection as in the page would still show the paragraph div named toggle. Michael
Mitch said on 28.06.2010. 11:42
Ok, so if you want to have your own text for the toggle you need to hardcode the class "togglelink" onto the a tag that's required and then use the following code in your script...
// Andy Langton's show/hide/mini-accordion - updated 23/11/2009
// Latest version @ http://andylangton.co.uk/jquery-show-hide
// this tells jquery to run the function below once the DOM is ready
$(document).ready(function() {
// initialise the visibility check
var is_visible = false;
// hide all of the elements with a class of 'toggle'
$('.toggle').hide();
// capture clicks on the toggle links
$('a.togglelink').click(function() {
// switch visibility
is_visible = !is_visible;
// toggle the display - uncomment the next line for a basic "accordion" style
//$('.toggle').hide();$('a.togglelink').html(showText);
$(this).parent().next('.toggle').toggle('slow');
// return false so any link destination is not followed
return false;
});
});
Niconemo said on 29.06.2010. 10:48
Could not achieve to make the whole line a link instead of a "(show)" link as several persons want to do…
So I made it via some quite basic CSS :D
(100 % accessible of course and very customizable !)
.togglelink
{
display:block;
position:relative;
text-align:right;
margin-top:-1.2em;
z-index:99;
background:none;
color:#FFF; /* your background color here */
}
Greg said on 08.07.2010. 09:54
This all seems overly complicated. I achieved the same thing in a much simpler way.
I have a div with a class of "content" which contains my FAQs and then each title (the part people click on) is wrapped in a then the content that shows and hides is in a tag.
$(function () {
$("div.content div").slideUp(0);
$('div.content p').click(function () {
$(this).next().slideToggle(500);
});
});
Michele said on 10.07.2010. 12:02
I am the only one I couldnt get it to work fine; It 's everything ok but I cannot understand why I am getting This:
Section one: a div with a paragraph (Hide) (Show)
You can show/hide an entire div by giving it a class of "toggle". links and other child elements will work fine too. The element directly before this one is a heading, so it gets a show/hide link appended.
Section two: single paragraph (Show) (Show)
A single paragraph can be hidden by giving it a class of toggle too. I can't help but be impressed by how easy it is to use jquery - even for someone with limited programming and javascript experience like me. Again, the preceding element is a heading.
Now: a list (Show) (Show)
I mean, I get two links : (show) (Show) or (hide ) (hide)
Thanks anyway
Michele
Michele said on 11.07.2010. 23:42
this is the code is pull out from your script: Section one: a div with a paragraph Learn More Learn More Learn More Learn More Learn More any idea why?
Simon said on 15.07.2010. 22:00
Colin: "There seems to be a problem with the text in IE it looks different to the "unhidden" text, lighter and rather spider like"
Me too - it's the weirdest thing. I read your comment and just assumed you didn't know much about CSS (sorry!), but then checked it out myself in IE7 and was amazed. I use Cleartype - it seems that everything in the revealed div has Cleartype removed. A quick Google reveals this to be a known issue, specific to the combination of jQuery's fadeIn/fadeOut / Cleartype / IE7. There are some fixes out there, but none of them are as simple as I'd like... oh well.
Thanks a million for the script, anyway, Andy.
Neil said on 26.07.2010. 12:21
This is great - how would you tweak it so that showing one div hides the others, so that only one div is ever visible at a time?
John Sharp said on 09.08.2010. 04:49
Great piece of code - thanks!
I needed something that would work for a ton of auto-created tab panels - came up with a simple version of this that may be of interest to others...
Step 1: Make all the divs you wish to control class='toggle' and make each style='display:none;' except the one you want to show on page load
Step 2: Iterate this for each tab and div you need to hide/show
$().ready(function() {
$('#link_show_1').click(function() {
$('.toggle').hide();
$("#div_show_1").toggle();
return false;
});
});
Andy said on 13.08.2010. 15:55
Thanks a huge stack! I've been using the css hidden value, which doesn't show up in SEO or with javascript off, so this is perfect!
Rayaan said on 18.08.2010. 12:10
Hi - thanks for the script - great work. We're using this script as a menu and searching for a possibility to have a special toggle-section opened on page load. Any idea on how to solve this? Thanks for help, Rayaan.
Fred Riley said on 25.08.2010. 15:47
Thanks, Andy, that was just what I was looking for. I was after displaying search results in brief with a [more] link toggling to [less] but couldn't figure out how to do it for multiple elements independently, short of giving each element a specific id which is clunky. Your script does the job perfectly, and has saved me some hours of trial and error. Much appreciated :)
Chuck said on 26.08.2010. 02:42
Awesome! I am using it for a FAQ page. I do have a question. I attempted to use $(".toggle").prev().wrap('); to use my question as the link that opens the answer. However, instead of the answer I get the Show link and Hide link, which do nothing really. Any ideas on that? Tested in IE7, IE8, Firefox.
Thanks in advance!!!
Recent Responses:
Page last (manually) updated: December 23, 2009.
Questions, comments, insults or praise? Have your say: