London
London

Reputation: 15274

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

Upvotes: 4

Views: 4404

Answers (4)

Frédéric Hamidi
Frédéric Hamidi

Reputation: 262979

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.

Upvotes: 6

calvinf
calvinf

Reputation: 3924

Rather than unbinding/binding the click event, you could check the state of another variable to see if it should do the action.

var MyObject = {
  requestActive = false;
};

function MyJsonFunction() {
  // when requesting
  MyObject.requestActive = true;
  //...
  // when request over
  MyObject.requestActive = false;

}

$("#elem").click(function{
  if (MyObject.requestActive == true) {
    //do something
  }
});

Upvotes: 0

jondavidjohn
jondavidjohn

Reputation: 62392

You are looking for .unbind(). Pass it 'click' and it will destroy the click event.

I would put it just before your getJSON and re-bind the click event inside the success handler of your ajax call.

Upvotes: 2

gearsdigital
gearsdigital

Reputation: 14205

You have to do some additional scripting. There is no callback for that. Take a look over here: jQuery - How can I temporarily disable the onclick event listener after the event has been fired?

Upvotes: 0

Related Questions