sparecycle
sparecycle

Reputation: 2058

How to nullify click event that is bound to an element?

I see how you might do this with an onclick event: How do you override inline onclick event?

However there is an event which seems to be bound to a specific HTML element that I would like to remove/nullify.

Here is how it is bound with jQuery:

  $('.play-control').bind('click', function(evt){
        player.play();
  });

Using the SE link I provided above does not "disassociate" the original binding. Seems to only work with onclick events.

How then would I "unbind" an event binding in Javascript (or jQuery)?

Upvotes: 1

Views: 414

Answers (2)

imvain2
imvain2

Reputation: 15857

Event handlers attached with .bind() can be removed with .unbind(). (As of jQuery 1.7, the .on() and .off() methods are preferred to attach and remove event handlers on elements.) In the simplest case, with no arguments, .unbind() removes all handlers attached to the elements: http://api.jquery.com/unbind/

According to Jquery, use of off and on is preferred

$(document).bind('click', '.play-control', function(evt){
        player.play();
  })

    $('.play-control').off('click');

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1075159

You can unbind all click handlers hooked up with jQuery using unbind or, with more up-to-date versions of jQuery, off:

$('.play-control').unbind('click');
// or
$('.play-control').off('click');

But unless you can change that code hooking up that handler, you can't unhook just that specific one without delving into jQuery internal data structures which can change without notice between dot releases.

If you can change that code, here are two ways you could target just that handler:

1. Use a named function:

Hooking it up:

function playClick(evt){
    player.play();
}
$('.play-control').on('click', playClick);   // Or use `bind`

Unhooking it:

$('.play-control').off('click', playClick);  // Or use `unbind`

2. Use an "event namespace":

Hooking it up:

$('.play-control').on('click.play', function(evt){ // Or use `bind`
    player.play();
});

Unhooking it:

$('.play-control').off('click.play');  // Or use `unbind`

Note the .play added to click.

More in the documentation: on, off

Upvotes: 1

Related Questions