Search code examples
jqueryremoveclassjquery-masonryparents

.parents().removeClass() not working


i got this javascript, trying to remove a class on a parent element:

$(this).parents(".box").removeClass("expanded");

on this html:

<div class="box trx">
<a href="javascript:;" class="open-content"><?php the_post_thumbnail('thumbnail'); ?></a>
<div class="expandable">
    <?php the_content(); ?>
    <span class="simple">
        <a class="cunload" href="javascript:;">Close</a>
    </span>
</div>
</div>

Unfortunately, this doesn't work so far. I've done several tests like:

$(this).parents(".box").removeClass("trx");

and

$(this).parents(".box").addClass("exd");

It all works. I'm using jQuery 1.6.2 and jQuery masonry on a wordpress site. There's a live demo here to see it all (not)working. Basically it works but the fact that the class isnt removed from the div does reopen instantly the div and its content. Am pretty confused on why it does not remove the .expanded class.

EDIT: i just understood that the class is there yet when the document is loaded. It's being added afterwards on a click on a picture, therefore i think my removing problem comes from this. Sorry for the misguiding explanation.


Solution

  • You have a click handler on the .box element.

    And inside it you have a click handler on the .cunload element.

    Since the .cunload is nested in the .box both elements receive the click event when you press the close button, and so it re-opens.. (due to events bubbling up the DOM hierarchy)

    Change your .cunload handler to

    $('.cunload').click(function(e){
                e.stopPropagation();
                restoreBoxes();
                $(this).parents(".box").removeClass("expanded");
    });