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.
$.fn.click1 = function(fn) {
  $(this).data('clicked', false);
  $(this).click(function(o) {
    if ($(this).data('clicked')) return false;
    $(this).data('clicked', true);
    fn(o);
    return false;
  });
};

(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.

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

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.)