Suppress jQuery event handling temporarily
jquery, jquery-plugins
Solution
I realize this question is old, but I found it while seeking an answer to the same question, and ended up finding a different solution that works well in simple applications of event handlers.
$(element).click(function(e) {
e.preventDefault();
// Check for fired class
if ($(this).hasClass('fired') == false) {
// Add fired class to all instances of element
$(element).addClass('fired');
// Do the rest of the function...
// Remove fired class to 'reactivate' events
$(element).removeClass('fired');
}
}
Simply adding a class to your 'element's while the code from the event is firing allows you to prevent further code from being executed as the result of another click event. So while you're not actually preventing any other click events, you're preventing the resulting code from running. Simple, crude, ignores the heavily preached use of bind and unbind, but works.
Problem
Is there an elegant way to temporarily suppress jQuery events? I use code like this: ``` $(element).unbind(event, function1).unbind(event, function2); // code for which the event is suppressed $(element).bind(event, function1).bind(event, function2); ``` but I find it a bit clumsy and not very scalable to many events. Why do I want to suppress events temporarily? I use BlockUI plugin to block UI during Ajax access. This is done with: $().ajaxStart($.blockUI).ajaxStop($.unblockUI) as proposed by BlockUI. However, one Ajax access is special, so I need a different message. The ajaxStart and ajaxStop events interfere with the message code (nothing is shown): ``` function message(text, callback) { if (text == undefined) { $.unblockUI(); return; } // $().unbind('ajaxStop', $.unblockUI).unbind('ajaxStart', $.blockUI); $("#message_text").html(text); $.blockUI({message: $("#message")}); $("#message_ok").click(function() { // $().bind('ajaxStop', $.unblockUI).bind('ajaxStart', $.blockUI); $.unblockUI(); if (callback != undefined) callback(); }); } ``` Only if I uncomment the unbind() and the bind() lines, it is working.