Take the 2-minute tour ×

How can I store which events were removed with unbind and re-apply them later?

Suppose that I have this element:

<div id="thediv">The Div</div>

Which has a varying number of functions attached to its onclick event. I know I could use unbind to remove all the onclick functions:


How can I store the unbound functions so as to re-bind them later?

Note that this must work with jQuery 1.5.

I did see this previous answer , but there a couple of things I didn't understand about it:

  • Why is it binding first and then unbinding?
  • What is ary_handlers[idx] doing?

(I'm not really looking for answers to these questions, unless they are necessary to explain the solution for my question about capturing the unbound functions.)

share|improve this question

1 Answer 1

up vote 3 down vote accepted

I think you could do something like this: you store the events of the div by cloning the div and saving data('events') in an object. Afterwords you iterate on the object and bind back the events. You have to clone because when you unbind the events the original data('events') are deleted.(hope i understood what you are looking for)

<div id='my'>my</div>

var my = $('#my');

$(this).css('color', 'red');


var ev =my.clone(true).data('events');


for (var e in ev){
    //you have to iterate on the property since is an array with all the handlers for the same event)
    for (i= 0; i < ev[e].length; i++){
       my.bind(e, ev[e][i]);   

fidlle http://jsfiddle.net/pXAXW/

EDIT - To make this work in 1.5.2 you just need to change the way you attach back the events because they are saved differently:


   var theDiv = $("#thediv");

     $(this).css("border-color", "blue");

   var theEvents = theDiv.clone(true).data("events");

   //  Unbind events from the target div

   //  Put the saved events back on the target div
   for (var e in theEvents){
     //  must iterate through since it's an array full of event handlers
     for ( i=0; i<theEvents[e].length; i++ ){
       theDiv.bind(e, theEvents[e][i].handler);


fiddle here: (the same as Katiek) http://jsfiddle.net/nicolapeluchetti/CruMx/2/ (the event is triggered twice if you don't click exactly on the div!) I also updated my fiddle to use jquery 1.5.2 http://jsfiddle.net/pXAXW/1/)

share|improve this answer
This works great with jQuery 1.6.2 (jsfiddle.net/UZW6T/1), but unfortunately it does not work with 1.5.2 (jsfiddle.net/CruMx/1). –  KatieK Jul 28 '11 at 18:20
To make it work with 1.5.2 it only needs to change something in the way you bind the events, because they are saved in a different way: look at my answer –  Nicola Peluchetti Jul 28 '11 at 19:17
The second block of code works w/ jQuery 1.5. Thanks! –  KatieK Aug 2 '11 at 15:28

Your Answer


