• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 521
  • Last Modified:

jQuery: How do I remove an .on(...) event handler correctly?

I can remove an (object selector).on('focus',..) event handler by using (object selector).off('focus') but of course if there is another 'focus' event handler that will get removed as well.

Is there a way to just remove the event handler I added and not remove any others?
0
purplesoup
Asked:
purplesoup
1 Solution
 
Chris StanyonCommented:
You would need to use a named function rather than an anonymous function when binding the focus event. Normally, you use an anonymous function:

$('#someElement').on('focus', function(e) { alert("Focused") });

Open in new window

Instead, create an eventHandler and use that:

//The eventHandler
function myFocusEvent(e) { alert("Focused") }

//Bind the focus event to the eventHandler
$('#someElement).on('focus', myFocusEvent);

Open in new window

You can then specifically remove that eventHandler:

$('#someElement').off('focus', myFocusEvent);

Open in new window

0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now