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(); } );
</script>

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

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

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. You can leave a response, or trackback from your own site.

Leave a Reply

Your comment


7 + one =