Monday, August 22, 2011

Preventing double-clicks in jQuery/Ajax-y handlers

Throwing this out there to see what people thing--I suspect there are better, cleaner ways to do this, and I'm wondering what they are.
  1. $.fn.click1 = function(fn) {  
  2.   $(this).data('clicked'false);  
  3.   $(this).click(function(o) {  
  4.     if ($(this).data('clicked')) return false;  
  5.     $(this).data('clicked'true);  
  6.     fn(o);  
  7.     return false;  
  8.   });  
  9. };  

(I return false because I know I don't want to follow the link; it'd be cleaner to return the results of the function call.)

I use the the same way I use the normal jQuery click() function. As a hack it served its purpose; I'm curious what issues there are with it, and how real jQuery developers handle this.

Updated: This already exists in the jQuery API.

  1. $("#foo").one("click", function() {  
  2.   alert("This will be displayed only once.");  
  3. });  

The documentation states that the handler is unbound after the first click. In my defense, originally the behavior was different after the first click--in other words, it wasn't as simple as one() allows, and I thought I was going to need the DOM element data. Which I didn't.

Oddly enough, my Google Fu failed me on this one, because this didn't show up on the first page of search results.

2 comments:

prodrive555 said...

http://api.jquery.com/one/

Dave Newton said...

Oh, yeah, that's probably better.

(Originally the behavior was going to be different for the second click--never looked beyond what I'd already written.)