EVENT HANDLERS-How to remove them with jQuery

You already voted!
Remove Event Handler

Table of Contents

jQuery

This can be done by using the unbind function. You can add multiple event handlers to the same object and event in jquery. This means adding a new one doesn’t replace the old ones.

Example 1:

$('#user_pic').click(function() { return false; }); // Adds another click event
$('#user_pic').off('click');
$('#user_pic').on('click.mynamespace', function() { /* Do stuff */ });
$('#user_pic').off('click.mynamespace');

UNBIND TO REMOVE A SINGLE EVENT

Example 2:

$('#myimage').unbind('click');

The following syntax might be quite helpful if you just want to remove an event:

 $('.user').bind('click', function() {
 $(this).unbind('click', arguments.callee); });

The unbind is just an event handler. Therefore, it needs to verify that the one unique anonymous-function handler is deleted using arguments.callee, resulting in a single time handler for a given event. 

REMOVE ALL EVENT HANDLERS

Likewise, having the simple HTML structure without all the event handlers associated with the element and its descendant nodes means removing all event handlers. The clone() function in jQuery comes in useful for this.

var original, clone;
original = $('#user');
clone = original.clone();
original.replaceWith(clone);

Leave a Comment

Your email address will not be published.