Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my second jQuery anonymous function not run when called?

Tags:

jquery

Take a look at this piece code below:

$(document).ready(function() { 
    $('a.upvote-off').click(function() {
        $(this).removeClass('upvote-off').addClass('upvote-on');
    });
    $('a.upvote-on').click(function() {
        $(this).removeClass('upvote-on').addClass('upvote-off');
    });
});

It's a simple jQuery toggle function which removes a class upvote-off of an anchor tag, then replaces it with upvote-on. Likewise, the second portion of the code reverses the initial code when the same icon is clicked on again. The default value of the anchor tag is upvote-off.

The first portion of the function runs:

$('a.upvote-off').click(function() {
    $(this).removeClass('upvote-off').addClass('upvote-on');
});

However, the second doesn't work:

$('a.upvote-on').click(function() {
    $(this).removeClass('upvote-on').addClass('upvote-off');
});

Yet, if I comment out the first portion, the second portion works. Why is this?

Note that I'm not using .toggleClass() because there's some more complex functionality I want to add in to each at a later point.

like image 911
marked-down Avatar asked Aug 24 '26 02:08

marked-down


1 Answers

The problem is that you're binding your handlers only to the elements that have the specified classes when the page is first loaded. If an element's class changes, the bindings don't automatically follow it.

To solve this, use delegation with .on().

$(document).ready(function() { 
    $(document).on('click', 'a.upvote-off', function() {
        $(this).removeClass('upvote-off').addClass('upvote-on');
    });
    $(document).on('click', 'a.upvote-on', function() {
        $(this).removeClass('upvote-on').addClass('upvote-off');
    });
});

If there's a smaller DIV that encloses all the upvote elements, replace document with that ID to minimize the overhead of this.

like image 107
Barmar Avatar answered Aug 26 '26 16:08

Barmar



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!