Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery function prevents add / remove class on click

I'm trying to have a div get a new class (which makes it expand) when being clicked, and get it back to the old class (which makes it close) when clicking on a cancel link inside that div.

<div class="new-discussion small">
    <a class="cancel">Cancel</a>
</div>

<script>
    $('.new-discussion.small').click(function() {
        $(this).addClass("expand").removeClass("small");
    });
    $('a.cancel').click(function() {
        $('.new-discussion.expand').addClass("small").removeClass("expand");
    });
</script>

Now, adding the expand class works flawlessly, but closing the panel after clicking on the cancel link only works when I remove this code:

$('.new-discussion.small').click(function() {
    $(this).addClass("expand").removeClass("small");
});

So I guess this must be preventing the second function to work, but I really can't figure out why.

Any ideas? Thanks!

like image 922
Lennart Avatar asked Dec 03 '25 16:12

Lennart


1 Answers

Try this

$('a.cancel').click(function() {
    $('.new-discussion.expand').addClass("small").removeClass("expand");
    return false;
});

Reason may be your click event is getting propagated to parent which is also listening to click event.

like image 162
Sachin Avatar answered Dec 06 '25 04:12

Sachin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!