Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Class Selector still firing after removeClass

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');
    });
like image 472
JMichaliga Avatar asked Dec 29 '09 18:12

JMichaliga


People also ask

How do you remove an active class?

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.

What is removeClass in jQuery?

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.


1 Answers

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

like image 101
meder omuraliev Avatar answered Sep 24 '22 17:09

meder omuraliev