marked-down
marked-down

Reputation: 10428

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

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.

Upvotes: 3

Views: 177

Answers (1)

Barmar
Barmar

Reputation: 782785

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.

Upvotes: 8

Related Questions