Search code examples
jquerytoggleshow-hide

jQuery hide and show collapse multiple divs


I need to be able to hide and show divs on a page.

I need one active by default then when I click on other links to show another div, I need the active div to hide, and so on. So only one div is open at one given time.

I have put a demo together to show what I require, I have got it working so to speak, but I need it to collapse/hide the active div once another link is clicked.

http://jsfiddle.net/QFfzs/3/


Solution

  • You need to add a class to the divs you're trying to hide, then hide the all divs before toggling like this:

    //adding '.hideMe' to the divs to be toggled
    $(document).ready(function() {
        $('#hideDetailsDiv').hide();
        $('a#hideDetailsButton').click(function() {
            if (!$('#hideDetailsDiv').is(':visible')) {
                $('.hideMe').hide(400);
            }
            $('#hideDetailsDiv').toggle(400);
        });
    });
    

    JSFiddle: http://jsfiddle.net/QFfzs/4/

    Updated JSFiddle: http://jsfiddle.net/QFfzs/5/ (done with less code)