I am allowing users to upvote an item. When they click the up arrow, I have jQuery change the class of the arrow so that it turns green. Now, if the user clicks that same arrow again, I want to create an event to change that arrow back to its original class, so they are undoing their vote (like stackoverflow voting: click once to upvote, click again to undo). Anyway here is my code.
These are the arrow classes in php generated on page load.
<a href="javascript:void(0)" id = "' . $row['item_id'] . 'up"
'; if ($row['upVote'] > 0) { echo '
class = "used_upArrow"
';} else {echo '
class = "new_upArrow"
';} echo '
rowid="' . $row['item_id'] . '">
</a>
Here is my jQuery changing the class on an upvote (among other things). This all works perfectly.
//upArrow
$('.new_upArrow').click(function(){
var row = $(this).attr('rowid');
$.ajax({
type: "GET",
url: "upVote.php?id="+row,
cache: false,
async: false,
success: function() {
$('.'+row).html(parseInt($('.'+row).html()) + 1);
document.getElementById(row+'up').className = "used_upArrow";
},
error: function(result){
alert('Voting error, please try again.');
}
});
});
Here is where the undoing should occur. So, new_upArrow should now be used_upArrow, and this script should fire on click.
$('.used_upArrow').click(function(){
var row = $(this).attr('rowid');
$.ajax({
type: "GET",
url: "downVote.php?id="+row,
cache: false,
async: false,
success: function(result) {
$('.'+row).html(parseInt($('.'+row).html()) - 1);
document.getElementById(row+'up').className = "new_upArrow";
},
error: function(result){
alert('Voting error, please try again.');
}
});
});
Checking firebug, the class is in fact changing FROM new_upArrow TO used_upArrow, but it continues to UPVOTE when clicked as if the class has no changed. Any ideas what is going on? Thank you in advance.
Use jQuery live event binding, eg
and
The reason your event binding isn’t working is because the normal bind, eg
element.click()is processed only once at the time of execution.The live binder uses event delegation which will attach the handler to matching elements now and in the future.