Follow this Blog!

May 20, 2013

f Comment

[SOLVED] jQuery: How Do You Unbind And Rebind the Same Event Handler Later?

Amazon How do I unbind and later rebind the same event handler? How do you detach, for example, the mouse click handler from a jQuery selector and later reattach the original mouse click handler to the same jQuery selector?

This idea is useful in situations where you would like to temporarily disable mouse clicks in some jQuery selector, and later enable the exact same onclick behavior in that selector again.

Obviously this idea applies to other JavaScript events such as mouseover and mouseleave.

After extensive searches on the Internet I couldn't find answers. Some solutions suggest calling unbind() but it just doesn't work for me. When I finally managed to solve this problem by myself I thought to myself "I am so writing a post about it on my blog." So here you are.

First you save the original click behavior in a variable clickHandler. When you want to disable the click handler you set $("#carousel").data("events")['click'] to null. Later when you want to re enable the click handler set $("#carousel").data("events")['click'] to clickHandler.

Here's an example of unbinding click handler when mouse is hovered over the 'carousel' DOM element and rebinding the original click handler when mouse leaves the DOM element.
var clickHandler= $("#carousel").data("events")['click'];
('#carousel').bind('mouseenter', function(){
}).bind('mouseleave', function(){
That's it! Read on to learn how works.

According to jQuery document "Calling retrieves all of the element's associated values as a JavaScript object. Note that jQuery itself uses this method to store data for internal use, such as event handlers, so do not assume that it contains only data that your own code has stored."

Let's say you have a DOM element with attribute id set to carousel. If you run $("#carousel").data("events") in Chrome's web developer toolbar console you'll see the following response.

Object {mouseover: Array[2], click: null, mouseout: Array[2], mousedown: Array[1], mouseenter: Array[1]...}
  click: Array[1]
  mousedown: Array[1]
  mouseenter: Array[1]
  mouseleave: Array[1]
  mouseout: Array[2]
  mouseover: Array[2]
  __proto__: Object

As you can see this selector has the following event handlers attached to it: click, mousedown, mouseenter, mouseleave, mouseout, mouseover.

Let's say you'd like to unbind click handler and rebind it later. Read the section above to see how it's done!

Related Article
jQuery: How Do You Bind a Handler to an Event From Scratch?

Questions? Let me know!
Please leave a comment here!
One Minute Information - by Michael Wen
Find Michael on Facebook
ADVERTISING WITH US - Direct your advertising requests to Michael