Brian
Brian

Reputation: 37

Show/hide toggle, and adding classes

I'm creating an FAQ page.

I want to toggle the answers open and closed. I have that working using jquery.

I also want to add a class (.active) to the selector that is "open". I can add the class to the parent.

My problem is this: I need to use unclassed elements, because the end-user will not understand adding classes. It needs to be un-styled block elements. So it looks like this:

<h3 class="active">Activator</h3>
  <p>show</p>
<h3>Activator</h3>
  <p>hide</p>
<h3>Activator</h3>
  <p>hide</p>
etc... 

When the script adds the class .active to the h3 that is clicked, it adds the class .active to ALL the h3 tags.

Here is my code:

$(document).ready(function() {
    $('.content p').hide();
    $('h3').click(function(){
        $(this).next("p").toggle(250);
    });
    $(".content h3").click(function(){
        $(".content h3").toggleClass("active");
    });
});

Link: working demo/site Thank you in Advance.

Upvotes: 0

Views: 92

Answers (1)

gilly3
gilly3

Reputation: 91637

This is because you are selecting all the elements in your click handler with $(".content h3"). Instead, you need to reference this to get just the element that was clicked:

$(document).ready(function() {
    $('.content p').hide();
    $('h3').click(function(){
        $(this).next("p").toggle(250);
    });
    $(".content h3").click(function(){
        $(this).toggleClass("active");
    });
});

Edit: A nice trick would be to set up your CSS like this:

.content p
{
    display: none;
}
.content h3.active + p
{
    display: block;
}

By using the adjacent sibling combinator (+) you control the display of the <p> based on whether your <h3> is active. You can then simplify your JavaScript:

$(document).ready(function() {
    $(".content h3").click(function() {
        $(this).toggleClass("active");
    });
});

You lose your animation this way, but then you could add it back in with a CSS3 transition.

Edit: Transitioning height is tricky if the height is not fixed. It can be accomplished by transitioning max-height, but when collapsing, there can be a delay. You can play with the values to get something that works pretty well. Here's what I came up with: jsfiddle.net/FsVPn

Upvotes: 2

Related Questions