0

Using jQuery, I have an element with multiple event handlers set different ways. The code is long, legacy code, so I would like to change as little as possible. However, I need to, at different times, remove ALL the event handlers at once.

Below is an example of the various handlers attached to the element:

$('#myElement').focus( function() {//Do Something} );
$('#myElement').keydown( function() {//Do Something} );
$('#myElement').submit( function() {//Do Something} );
$('#myElement').bind( function() {//Do Something} );
$('#myElement').click( function() {//Do Something} );

My question: Can all of these be removed with one call of .off()?

$('#myElement').off();

Or do they all need to use .on to be removed with .off?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Justin Elkow
  • 2,833
  • 6
  • 28
  • 60
  • 1
    yes you can.`$('#myElement').off();` is perfectly valid syntax to remove all attached event for jquery 1.8+version – Milind Anantwar Oct 16 '14 at 18:07
  • Tip for futur questions. Usually, when the question start by *"Can"*, you can answer it by trying it! – Karl-André Gagnon Oct 16 '14 at 18:13
  • Another tip... [the jQuery documentation and the first result](http://api.jquery.com/off/) of [this Google search](https://www.google.com/search?client=safari&rls=en&q=jquery+off&ie=UTF-8&oe=UTF-8) says exactly this: _"Calling `.off()` with no arguments removes all handlers attached to the elements."_ – Sparky Oct 16 '14 at 18:13

2 Answers2

1

Yes those can be turned off with .off

$("#myElement").off(); //unbinds everything
tymeJV
  • 103,943
  • 14
  • 161
  • 157
1

off( events [, selector ] [, handler ] )

Remove an event handler.

events

Type: String

One or more space-separated event types and optional namespaces, or just namespaces, such as > "click", "keydown.myPlugin", or ".myPlugin".

If you want to remove a list of specific handlers pass them via first parameter.

$("#myElement").off("keydown click focus submit")

If you want to remove all, $("#myElement").off() will remove all event handlers.

JSFIDDLE

Community
  • 1
  • 1
Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474