mononym
mononym

Reputation: 2636

Prevent multiple click across elements (JQuery)

I have an array of anchors, I am binding an event to each one:

$j('.opts a').live("click", function(e){}) ;

I would like to stop the other anchors from being clickable until this click event has finished.

$j('.opts a').live("click", function(e){
  $j('.opts a').unbind('click'); 
  //do something
  $j('.opts a').bind('click');
});

This is just an example of one thing i've tried, but even the unbind doesn't work.

Upvotes: 2

Views: 1268

Answers (3)

Aaron Digulla
Aaron Digulla

Reputation: 328556

I don't think jQuery is the correct tool here. Your problem is that the events queue while your JavaScript does something.

So what you really need is something like "swallow all queued click events when I return."

I suggest to move the rebinding of the click handlers into a new function and call that in a timer. That allows the browser to process the queued events.

And maybe unbinding is the wrong approach as well. If you're always using the same handler, turn it into an object with a skip property:

skip: false,
run: function( e ) {
    if (this.skip) return;

    this.skip = true;

    ... do something ...

    var self = this;
    setTimeout( function() { self.skip = false; }, 50 );
}

[EDIT] Another alternative: If all the links are in one HTML element (like a parent div or something), you can install a click handler for that element which does nothing. That would also swallow the click events. You will still need the timeout handler to make sure the events are processed after you return from your function.

Upvotes: 2

Ohgodwhy
Ohgodwhy

Reputation: 50767

Bad ->

$j('.opts a').live("click", function(e){
  $j('.opts a').unbind('click'); 
  //do something
  $j('.opts a').bind('click');
});

Good ->

$j(document).on("click", '.opts a', function(e){
  $j('.opts a').off('click'); 
  //do something
  $j('.opts a').on('click', //a function such as 'myClickFunction' referencing what you want to occur.);
});

Upvotes: 0

Jarrett Meyer
Jarrett Meyer

Reputation: 19573

You can't really keep a link from being clickable. You can only unbind whatever JS event you've registered. You'll want to make sure to call preventDefault(), otherwise a link will just follow its href.

Try something like this.

var isDoingSomething = false;
$j('.opts a').on('click', function (e) {
    e.preventDefault();
    if (!isDoingSomething) {
        isDoingSomething = true;
        // do something
        isDoingSomething = false;
    }
});

Hope this helps.

Upvotes: 2

Related Questions