Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery remove and add back click event

Is it possible to remove than add back click event to specific element? i.e

I have a $("#elem").click(function{//some behaviour});, $(".elem").click(function{//some behaviour});(there are more than 1 element) while my other function getJson is executing I'd like to remove the click event from the #elem, and add it again onsuccess from getJson function, but preserve both mouseenter and mouseleave events the whole time?

Or maybe create overlay to prevent clicking like in modal windows? is that better idea?

edit :

I've seen some really good answers, but there is one detail that I omitted not on purpose. There are more than one element, and I call the click function on the className not on elementId as I stated in the original question

like image 637
London Avatar asked Feb 25 '23 05:02

London


1 Answers

Rather than using unbind(), which means you'll have to rebind the same event handler later, you can use jQuery's data() facility with the ajaxStart and ajaxStop events to have your elements ignore click events during all AJAX requests:

$(".elem").click(function() {
    if (!$(this).data("ajaxRequestPending")) {
        // some behaviour
    }
}).ajaxStart(function() {
    $(this).data("ajaxRequestPending", true);
}).ajaxStop(function() {
    $(this).removeData("ajaxRequestPending");
});

EDIT: This answer is also id-to-class-proof (see questioner's edit), since everything matching the selector will handle the AJAX events the right way. That's the main selling point of jQuery, and it shows.

like image 67
Frédéric Hamidi Avatar answered Mar 08 '23 12:03

Frédéric Hamidi