How to have slideToggle for multiple items on one page?

Anna Brila picture Anna Brila · May 25, 2013 · Viewed 8.1k times · Source

Im having problems with this code to work.. http://jsfiddle.net/whitewiz/z4fpx/

HTML

<h1 id="flip">Title<h1>
        <div id="panel">
            <p>Description that slides down</p>
        </div>

    <h1 id="flip">Title<h1>
        <div id="panel">
            <p>description that DOESN'T slide down</p>
        </div>

JavaScript

$(document).ready(function(){
  $("#flip").click(function(){
    $("#panel").slideToggle("slow");
  });   
});

and CSS

#panel,#flip
{
padding:5px;
text-align:center;
background-color:#e5eecc;
border:solid 1px #c3c3c3;
}
#panel
{
padding:50px;
display:none;
}

They work for first description, but doesn't work for the rest. I have about 18 #panels that should slide down, when I press on "Title" but only the first works.. Could you please find the missing piece in javascript that doenst allow multiple toggle?

Example on -> http://jsfiddle.net/whitewiz/z4fpx/

Answer

Nile picture Nile · May 25, 2013

The first one works because that is the first element in the DOM with that id. Generally it is bad practice to have the same id assigned to multiple elements. Instead, use classes, like this:

HTML:

<h1 class="flip">Title<h1>
<div class="panel">
    <p>Description that slides down</p>
</div>

<h1 class="flip">Title<h1>
<div class="panel">
    <p>description that DOESN'T slide down (but does now)</p>
</div>

CSS:

.panel,.flip
{
    padding:5px;
    text-align:center;
    background-color:#e5eecc;
    border:solid 1px #c3c3c3;
}
.panel
{
    padding:50px;
    display:none;
}

I assume you only want to expand the panel following the header that you clicked on, in which case you need to get the closest element with the class name "panel" that follows the "flip" that was clicked on.

$(document).ready(function(){
    $(".flip").click(function(){
        $(this).next().find(".panel").slideToggle("slow");
    });
});

Working example: http://jsfiddle.net/BBQJy/