jQuery: limiting events on the same element

Suppose that you have an element and you want a user click on it only three times. In jQuery, there's no native method to accomplish this task, so you have to develop a little workaround to fulfill this task. For example:

var counter = 0;

$('#test').bind('click', function(event) {

  counter++;
  
  alert('Test');
  
  if(counter == 3) {
  
    $(this).unbind(event);
  
  
  }

});

When your counter variable reaches 3, you remove the event handler by using unbind() and passing to it a reference to the current Event object. This workaround can be applied to all event types.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.