I have a number of clickable elements on a page that shouldn’t be enabled until a resource gets loaded. My idea was to initialize the buttons with a .disabled
class, which I would then remove when the resource was ready. In the meantime, I’d have a handler on the .disabled
click event that would prevent event propagation to the other handlers.
The problem is, even though I add the .disabled
handler first, I can’t get it to fire before the other click handlers.
$( "body" ).on('click','.disabled', function(e) { alert('disabled'); e.stopImmediatePropagation(); return false; }); $('.clickable').click(function(e) { alert('enabled'); }); // Call this when ready: //$('.clickable').removeClass('disabled');
FIDDLE: http://jsfiddle.net/4rJxU/7/
This will pop up an ‘enabled’ alert first, and then a ‘disabled’ alert, presumably because the delegated events are captured by the parent of the .clickable
elements, and are thus handled later?
How can I disable click handlers using delegated events?
Advertisement
Answer
This should work (without the need for the disabled class):
var clickEnabled = false; $('.clickable').on('click', function(e) { if (!clickEnabled) { alert('disabled'); e.stopImmediatePropagation(); return false; } else { alert('enabled'); } });
… And just set clickEnabled to true once whatever you need is ready.
Fiddle: http://jsfiddle.net/ehFGX/
If all you want is for the default click handler to fire once everything is ready, you can just remove the else block above and it will continue with the default if your handler doesn’t return false.
If you still prefer to use the disabled class, you can just check if $(this) has that class instead of checking !clickEnabled, too.