?
Solved

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

Posted on 2013-11-13
1
Medium Priority
?
501 Views
Last Modified: 2013-11-13
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
Comment
Question by:purplesoup
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
1 Comment
 
LVL 43

Accepted Solution

by:
Chris Stanyon earned 2000 total points
ID: 39644436
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

Why Off-Site Backups Are The Only Way To Go

You are probably backing up your data—but how and where? Ransomware is on the rise and there are variants that specifically target backups. Read on to discover why off-site is the way to go.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
This article discusses how to implement server side field validation and display customized error messages to the client.
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Suggested Courses

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question