danzo
danzo

Reputation: 301

jQuery close button for toggleClass and slideToggle not working as expected

I have a simple slide toggle setup that I want to add a close button to, but it seems that removeClass() isn't working.

When clicking the close link, I want to return to the previous color (remove .active) and leave open any others that are open. In other words, this close link should only affect the toggle that it's in. I thought it would be a simple matter of removing the "active" class from the title div and the content div and slide up the content div.

The slideUp part works fine, but the "active" class doesn't toggle off or remove.

Here's my js:

$("h2.titleTrigger").click(function(e){
e.preventDefault();
$(this).toggleClass("active").next().slideToggle("fast");
return false;
});

//CLOSE LINK
$(".closeIt").click(function(e){
 e.preventDefault();
$(this).closest(".toggleContent").slideUp("fast");
$(this).closest(".toggleContent").removeClass("active");
$(this).closest("h2.titleTrigger").removeClass("active");
 });

Fiddle here

I've also tried toggleClass instead of removeClass, but that doesn't work either. Where did I go wrong?

Upvotes: 0

Views: 2777

Answers (3)

Lyn Headley
Lyn Headley

Reputation: 11588

you're not selecting the element; closest() will never find the h2.

Try this instead:

$(this).closest(".toggleContent").prev().removeClass("active");

fiddle:

http://jsfiddle.net/Gw63h/

Upvotes: 1

Mottie
Mottie

Reputation: 86413

The h2 is not inside the .toggleContent, nor is it associated with the close button, so try this instead (demo)

$(".closeIt").click(function (e) {
    e.preventDefault();
    $(this).closest(".toggleContent")
        .slideUp("fast")
        .removeClass("active")
        .prev("h2.titleTrigger").removeClass("active");
});

Upvotes: 1

carrabino
carrabino

Reputation: 1762

to answer your request:
"When closing, I want to leave open any others that are open. In other words, this close link should only close the toggle that it's in."

this fiddle should do it:
http://jsfiddle.net/acturbo/TpQff/1/

jquery:

$("h2.titleTrigger").click(function(e){
    e.preventDefault();
    //$(this).toggleClass("active").next().slideToggle("fast");
    $("#mydiv").slideToggle("fast");


return false;
});

//CLOSE LINK
$(".closeIt").click(function(e){
     e.preventDefault();
    $(this).parent().slideUp("fast");
    $(this).closest(".toggleContent").removeClass("active");
    $(this).closest("h2.titleTrigger").removeClass("active");
 });

html

<h2 class="titleTrigger">slide it</h2>

<div id="mydiv">
    <h2 class="closeIt">close  it</h2>
    inside div
</div>

Upvotes: 1

Related Questions