Unbind a click event, store it and re-add the event later with jQuery

By Frank Forte

My trusty junior developer Sean and I were quite frustrated trying to find a solution online for getting a click event from an element, removing it from the element, then re-adding the event with a condition.

For example, anything with the css class “remove” should ask “are you sure” before completing the default action. Rather than adding this “are you sure” confirmation script to every remove function on the website, we came up with this following little hack:

working example:

<script type="text/javascript">
// the function we want to run when someone clicks a button
var myFunction= function() {
alert('process button click');
// e.g. ajax call to delete an item
// bind a click event to our element so the function above runs
var obj = $('#obj');
obj.on("click", function(){ myFunction(); } );

This following "post load" script is added to the footer after all other javascript has run

<script type="text/javascript">
// get all our click events and store them
var x = $._data($(this)[0], "events");
var y = {}
for(i in x.click)
y[i] = x.click[i].handler;
// stop our click event from running
// re-add our click event with a confirmation
if(confirm("Are you sure?"))
// if they click yes, run click events!
for(i in y)
return true;
// if they click cancel, return false
return false;

This may seem a bit weird (why do we store the click events in the variable “y”?)

Originally I tried to run the handlers in x.click, but they seem to be destroyed when we call .off(“click”). Creating a copy of the handlers in a separate variable “y” worked. I believe this is because the .off(“click”) method removes the click event from our document, along with the handlers.

This entry was posted on Thursday, January 3rd, 2013 at 9:15 pm and is filed under JavaScript. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.