I am creating a little voting mechanism that sends a quick database timestamp through AJAX.
A series of buttons with the class "vote" are the triggers to vote, while there is text below to show how many "votes" are for that particular item.
After I run the AJAX method from the click event, I remove the "vote" class such that there cannot be more than one from that item. However my problem is that even with the class removed the trigger can still fire and increment as many votes.
Here is the HTML of the element:
<div class="points">
<img class="vote" src="images/up.gif" alt="'.$idea['id'].'">
<p class="vote-'.$idea['id'].'">'.$points.' Points</p>
</div>
Here's the jQuery Call:
$('.vote').click(function(){
var iID = $(this).attr('alt');
var typeString = "id="+iID;
$.ajax({
type: "POST",
url:"vote.php",
data: typeString,
success: function (txt){
$('.vote-'+iID).html('<p>'+txt+' Points</p>');
}
});
$(this).attr('src', 'images/voted.gif');
$(this).removeClass('vote');
});
removeClass() Method. This method removes one or more class names from the selected elements. If no parameter is specified in the removeClass() method, it will remove all class names from the selected elements.
The removeClass() method removes one or more class names from the selected elements. Note: If no parameter is specified, this method will remove ALL class names from the selected elements.
You're attaching the event handler to the DOM element, and it stays intact. You can either
a. set .data('triggered', 1)
like so:
if ( !$(this).data('triggered') ) {
// do code
$(this).data('triggered', 1);
}
b.
if ( $(this).hasClass('vote') ) {
// do code
}
c. use .live instead of .click, eg $('.foo').live('click', fn)
d. remove the event handler manually after invoking your code, $(this).unbind('click')
as the last line, after the remove class bit
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With