views:

40

answers:

3

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');
    });
+4  A: 

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

meder
+1  A: 

The class of a DOM element is used to reference it, not to alter its Event binding behavior.

To remove a DOM elements click event use unbind.

Luca Matteis
A: 

The selector is only evaluated once, when it's first called. It does not get re-evaluated every time an event is fired to check which elements match; that would be slow.

Chase Seibert