views:

93

answers:

1

Hiya,

I have the following markup

<div class="question">
    <h2>Title 1</h2>
    <div class="answer">content 1</div>
</div>

<div class="question">
    <h2>Title 2</h2>
    <div class="answer">content 2</div>
</div>

<div class="question">
    <h2>Title 3</h2>
    <div class="answer">content 3</div>
</div>

I want to toggle the class "active" when a question div is clicked. I've attempted this following code:

<script type="text/javascript" >
$(document).ready(function(){
    $(".question").click(function () {
        $(this).toggleClass("active");  
        $(this).find("h2").toggleClass("active");   
        $(this).find("answer").toggleClass("active");   
    });
});
</script>

But this unfortunately adds the class active to every question,h2 and answer, rather than just the one that was clicked. I can't seem to get the syntax correct.

Can anyone point me in the right direction?

Cheers, Shadi

+1  A: 

Try this, it will set whichever is clicked to active:

<script type="text/javascript" >
$(document).ready(function(){
    $(".question").click(function () {
        $(".active").removeClass("active");
        $(this).addClass("active");
        $(this).find("h2, div.answer").addClass("active");
    });
});
</script>

If a question is clicked on twice in a row it will stay active as opposed to toggling off. Or if you're actually looking to have a second click in a row make it inactive:

<script type="text/javascript" >
$(document).ready(function(){
    $(".question").click(function () {
        var isAlreadyActive = $(this).hasClass("active");
        $(".active").removeClass("active");
        if (!isAlreadyActive) {
            $(this).addClass("active");
            $(this).find("h2, div.answer").addClass("active");
        }
    });
});
</script>
Parrots
Seems my code didn't work because as highlighted in the comments i actually had an error in my html. But this improved what i did so i'm accepting it :) Cheers.
Shadi Almosri