Mukesh Agarwal
Mukesh Agarwal

Reputation: 11

How to make an event handler fire only once in JQuery for the Selectors with multiple items?

I have following JQUERY code.

<script type="text/javascript">
    $(".voteup").click(function(){
        alert($(this).parents(".webresource").attr("id"));
    });
</script>

The page has 4 elements with classname voteup. But when I click on one of them, alert is displayed four times. I would think that there is only one click so the event handler function would execute only once.

What do I do to ensure that the event handler function is executed only once.

Upvotes: 1

Views: 1486

Answers (1)

John Strickler
John Strickler

Reputation: 25421

.one() binds an event handler and the unbinds it on its first execution.

$('.upvote').one('click', function() {
   ...
});

Also, I'd make sure it's not being bound multiple times somehow as Ender suggests in your comments.

Upvotes: 4

Related Questions