tags:

views:

33

answers:

3

i have this code to show a loading image when i run an ajax call:

$('.event').live('click', function () {
    var spinner = $("<img src='/content/images/ajax-loader.gif' />").insertAfter(this);

the issue is that since its an async call, if you click a link multiple times, it will show up with multiple spinners. Obviously this is just the sympton as i dont want to allow another ajax call before the first one returns.

What is the best way to "disable" a link or a button during the window of an existing ajax call?

A: 

What you could do is removing the listener on the link after you clicked it (or adding a listener that will simply return false; to stop the event and then, after the ajax call is finished reassign the listener to the link. This way it is disabled for as long, as the request takes.

Therefore it might be good, to store the callback in a separate variable to ease the assignment.

philgiese
+2  A: 

Nice thing about .live() is that it is selector based.

Because the handler is triggered for elements with .event class, just change its class, and the handler won't fire anymore.

$('.event').live('click', function () {
    $( this ).toggleClass( 'event event_clicked' );
    var spinner = $("<img src='/content/images/ajax-loader.gif' />").insertAfter(this);

This will remove the event class, and replace it with event_clicked, so subsequent clicks on the element won't trigger the live() handler.

To restore functionality, just swap the classes again.

patrick dw
A: 
  1. You can hide the link, or replace it with something non-functional but visually similar.

  2. You can cover the link with a visually similar div that prevents people from clicking on it.

  3. You can insert a stateful switch that captures clicks on the link and calls event.stopPropagation().

When the AJAX call terminates, you can reset each of these to their prior state.

Elf Sternberg