Why does my second jQuery anonymous function not run when called? -
take @ 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 simple jquery toggle function removes class upvote-off
of anchor tag, replaces upvote-on
. likewise, second portion of code reverses initial code when same icon clicked on again. default value of anchor tag upvote-off
.
the first portion of function runs:
$('a.upvote-off').click(function() { $(this).removeclass('upvote-off').addclass('upvote-on'); });
however, second doesn't work:
$('a.upvote-on').click(function() { $(this).removeclass('upvote-on').addclass('upvote-off'); });
yet, if comment out first portion, second portion works. why this?
note i'm not using .toggleclass()
because there's more complex functionality want add in each @ later point.
the problem you're binding handlers elements have specified classes when page first loaded. if element's class changes, bindings don't automatically follow it.
to solve this, use delegation .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 smaller div encloses upvote elements, replace document
id minimize overhead of this.
Comments
Post a Comment