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

Suggested Alternative

Update: 11/1/12 For those having problems with images in the links, a solution has been proposed in the comments:

// Andy Langton's show/hide/mini-accordion - updated 11/01/2012
// modified 15/10/2011 by Johannes Georgi
// 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(' ...'+showText+'');
$('.toggle').prev().data('is_visible', true);

// hide all of the elements with a class of 'toggle'
$('.toggle').hide();

// capture clicks on the toggle links
$('a.togglelink').click(function() {

// switch visibility
$(this).data('is_visible', !$(this).data('is_visible'));

// change the link depending on whether the element is shown or hidden
$(this).html( (!$(this).data('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;

});
});
Category: 

Comments

Hi there. This is an

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?

brilliant, just what I was

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 Andy,

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!

Andy, this script is exactly

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.

This is really great...I am

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?

I'm having the same problem

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.

Sorry to be posting what I

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-...

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

Thanks for the instructions.

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);

Hi!

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

This is a great script. I

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?

Thanks a ton! This works like

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!

Thank you for sharing this

Thank you for sharing this code! Exactly what I needed for a project I'm working on.

Hi - thanks for the script -

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.

Thanks, Andy, that was just

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 :)

Awesome! I am using it for a

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!!!

I am still stuck. I have

I am still stuck. I have everything working beautifully (thanks) but want to have one div open by default with all of the others closed. I have tried John's script loaded at the bottom of the page and it doesn't seem to work. How do I have one panel open by default and all of the others closed?

Thanks a lot, can you give

Thanks a lot, can you give other animation examples..

Thanks a lot.................

Thanks a lot...............................................
script is great!

I'm extremely new to jQuery,

I'm extremely new to jQuery, and I really like this sample, but I current scenario on a site I'm building, and I can't figure out how to get my nav to work properly.

'this part contains 6 image buttons'

'this contains 5 image buttons.

There are 6 seperate "itemScene" divs, one for each of the first set of buttons. Each "itemScene" divs contains its own 5 buttons.

What I want to do is be able to click on a "itemNav" button, and have the appropriate "itemScene" div show, and the others hide.

I've tried several ways, but nothing seems to work. Could someone please help me.

Thanks

How would I add cookie

How would I add cookie support to this?

Good stuff. Thanks to Andy

Good stuff. Thanks to Andy for sharing and starting the thread. I borrowed some ideas here and applied to a toggle solution that I had already created. I use livequery cause it irons out bindings as applicable. I'm all about the show me, copy/paste stuff, so here's mine:

Show Details

Hello world. Hello world. Hello world.

Show Details

Goodbye world. Goodbye world. Goodbye world.

/* livequery info:
http://www.99points.info/2010/06/live-query-plugin-solution-of-your-prob...
http://plugins.jquery.com/project/livequery
*/
$(document).ready(function() {
var ShowText = 'Show Details' ;
var HideText = 'Hide Details' ;
$('a.toggle')
.livequery('click', function(event) {
var elemID = '#'+$(this).attr('rel');
if ( $(elemID).is(':hidden') ) {
$(elemID).show('slow') ;
$(this).html(HideText); // optionally comment out
} else {
$(elemID).hide('medium') ;
$(this).html(ShowText); // optionally comment out
}
return false;
});
});

Yes. I found its OK for every

Yes. I found its OK for every browser. Thanks for this great article.

Great script, thanks!

Great script, thanks!

Is there a way that I can use a class other than toggle? eg; I already have styles applied to the things I want to show/hide.

I tried just changing all instances of .toggle to my class but that didn't seem to work.

It's not a huge deal, I can just duplicate my class and call it .toggle, but just thought I'd ask.

Great, thank you so much –

Great, thank you so much – simple code that works. I appreciate your efforts!

Thanks for the code!

Thanks for the code!
Greet's from Brazil!

how do I keep the hide\show

how do I keep the hide\show status on the menu persistent when the page does a postback? for example I have multiple grid views on a page that update each other based on selection status and I lose my "hide" status each time I click on a grid. thanks.

Hello everyone!

Hello everyone!
After searching net I found this very useful script.I am using it in above site.
Please could any of You be so kind to write me a part of code in this script how to put images + and - to toggle instead of text.I went through all yours comments but I didn't notice anywhere that exact part of the code.
Greets from Croatia

Add new comment