Description: Attach an event handler function for one or more events to the selected elements.
The .on()
method attaches event handlers to the currently selected set of elements in the jQuery object. As of jQuery 1.7, the .on()
method provides all functionality required for attaching event handlers. For help in converting from older jQuery event methods, see .bind(), .delegate(), and .live(). To remove events bound with .on()
, see .off(). To attach an event that runs only once and then removes itself, see .one()
Event names and namespaces
Any event names can be used for the events
argument. jQuery will pass through the browser's standard JavaScript event types, calling the handler
function when the browser generates events due to user actions such as click
. In addition, the .trigger() method can trigger both standard browser event names and custom event names to call attached handlers. Event names should only contain alphanumerics, underscore, and colon characters.
An event name can be qualified by event namespaces that simplify removing or triggering the event. For example, "click.myPlugin.simple"
defines both the myPlugin and simple namespaces for this particular click event. A click event handler attached via that string could be removed with .off("click.myPlugin")
or .off("click.simple")
without disturbing other click handlers attached to the elements. Namespaces are similar to CSS classes in that they are not hierarchical; only one name needs to match. Namespaces should contain upper/lowercase letters and digits only.
In the second form of .on()
, the events
argument is a plain object. The keys are strings in the same form as the events
argument with space-separated event type names and optional namespaces. The value for each key is a function (or false
value) that is used as the handler
instead of the final argument to the method. In other respects, the two forms are identical in their behavior as described below.
Direct and delegated event handlers
The majority of browser events bubble, or propagate, from the deepest, innermost element (the event target) in the document where they occur all the way up to the body and the document
element. In Internet Explorer 8 and lower, a few events such as change
and submit
do not natively bubble but jQuery patches these to bubble and create consistent cross-browser behavior.
If selector
is omitted or is null, the event handler is referred to as direct or directly-bound. The handler is called every time an event occurs on the selected elements, whether it occurs directly on the element or bubbles from a descendant (inner) element.
When a selector
is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.
Event handlers are bound only to the currently selected elements; they must exist at the time your code makes the call to .on()
. To ensure the elements are present and can be selected, place scripts after the elements in the HTML markup or perform event binding inside a document ready handler. Alternatively, use delegated event handlers to attach event handlers.
Delegated event handlers have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated event handlers to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document
if the event handler wants to monitor all bubbling events in the document. The document
element is available in the head
of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.
In addition to their ability to handle events on descendant elements not yet created, another advantage of delegated event handlers is their potential for much lower overhead when many elements must be monitored. On a data table with 1,000 rows in its tbody
, this example attaches a handler to 1,000 elements:
1 2 3 |
|
An event-delegation approach attaches an event handler to only one element, the tbody, and the event only needs to bubble up one level (from the clicked tr
to tbody
):
1 2 3 |
|
Note: Delegated event handlers do not work for SVG.
The event handler and its environment
The handler
argument is a function (or the value false
, see below), and is required unless you pass an object for the events
argument. You can provide an anonymous handler function at the point of the .on()
call, as the examples have done above, or declare a named function and pass its name:
1 2 3 4 |
|
When the browser triggers an event or other JavaScript calls jQuery's .trigger()
method, jQuery passes the handler an Event object it can use to analyze and change the status of the event. This object is a normalized subset of data provided by the browser; the browser's unmodified native event object is available in event.originalEvent
. For example, event.type contains the event name (e.g., "resize") and event.target indicates the deepest (innermost) element where the event occurred.
By default, most events bubble up from the original event target to the document
element. At each element along the way, jQuery calls any matching event handlers that have been attached. A handler can prevent the event from bubbling further up the document tree (and thus prevent handlers on those elements from running) by calling event.stopPropagation()
. Any other handlers attached on the current element will run however. To prevent that, call event.stopImmediatePropagation()
. (Event handlers bound to an element are called in the same order that they were bound.)
Similarly, a handler can call event.preventDefault()
to cancel any default action that the browser may have for this event; for example, the default action on a click
event is to follow the link. Not all browser events have default actions, and not all default actions can be canceled. See the W3C Events Specification for details.
Returning false
from an event handler will automatically call event.stopPropagation()
and event.preventDefault()
. A false
value can also be passed for the handler
as a shorthand for function(){ return false; }
. So, $( "a.disabled" ).on( "click", false );
attaches an event handler to all links with class "disabled" that prevents them from being followed when they are clicked and also stops the event from bubbling.
When jQuery calls a handler, the this
keyword is a reference to the element where the event is being delivered; for directly bound events this is the element where the event was attached and for delegated events this is an element matching selector
. (Note that this
may not be equal to event.target
if the event has bubbled from a descendant element.) To create a jQuery object from the element so that it can be used with jQuery methods, use $( this )
.
Passing data to the handler
If a data
argument is provided to .on()
and is not null
or undefined
, it is passed to the handler in the event.data property each time an event is triggered. The data
argument can be any type, but if a string is used the selector
must either be provided or explicitly passed as null
so that the data is not mistaken for a selector. Best practice is to use a plain object so that multiple values can be passed as properties.
As of jQuery 1.4, the same event handler can be bound to an element multiple times. This is especially useful when the event.data
feature is being used, or when other unique data resides in a closure around the event handler function. For example:
1 2 3 4 5 6 7 8 9 |
|
The above code will generate two different alerts when the button is clicked.
As an alternative or in addition to the data
argument provided to the .on()
method, you can also pass data to an event handler using a second argument to .trigger() or .triggerHandler(). Data provided this way is passed to the event handler as further parameters after the Event
object. If an array was passed to the second argument of .trigger()
or .triggerHandler()
, each element in the array will be presented to the event handler as an individual parameter.
Event performance
In most cases, an event such as click
occurs infrequently and performance is not a significant concern. However, high frequency events such as mousemove
or scroll
can fire dozens of times per second, and in those cases it becomes more important to use events judiciously. Performance can be increased by reducing the amount of work done in the handler itself, caching information needed by the handler rather than recalculating it, or by rate-limiting the number of actual page updates using setTimeout
.
Attaching many delegated event handlers near the top of the document tree can degrade performance. Each time the event occurs, jQuery must compare all selectors of all attached events of that type to every element in the path from the event target up to the top of the document. For best performance, attach delegated events at a document location as close as possible to the target elements. Avoid excessive use of document
or document.body
for delegated events on large documents.
jQuery can process simple selectors of the form tag#id.class
very quickly when they are used to filter delegated events. So, "#myForm"
, "a.external"
, and "button"
are all fast selectors. Delegated events that use more complex selectors, particularly hierarchical ones, can be several times slower--although they are still fast enough for most applications. Hierarchical selectors can often be avoided simply by attaching the handler to a more appropriate point in the document. For example, instead of $( "body" ).on( "click", "#commentForm .addNew", addComment )
use $( "#commentForm" ).on( "click", ".addNew", addComment )
.
Additional notes
There are shorthand methods for some events such as .click() that can be used to attach or trigger event handlers. For a complete list of shorthand methods, see the events category.
Deprecated in jQuery 1.8, removed in 1.9: The name "hover"
used as a shorthand for the string "mouseenter mouseleave"
. It attaches a single event handler for those two events, and the handler must examine event.type
to determine whether the event is mouseenter
or mouseleave
. Do not confuse the "hover" pseudo-event-name with the .hover() method, which accepts one or two functions.
jQuery's event system requires that a DOM element allow attaching data via a property on the element, so that events can be tracked and delivered. The object
, embed
, and applet
elements cannot attach data, and therefore cannot have jQuery events bound to them.
The focus
and blur
events are specified by the W3C to not bubble, but jQuery defines cross-browser focusin
and focusout
events that do bubble. When focus
and blur
are used to attach delegated event handlers, jQuery maps the names and delivers them as focusin
and focusout
respectively. For consistency and clarity, use the bubbling event type names.
In all browsers, the load
, scroll
, and error
events (e.g., on an <img>
element) do not bubble. In Internet Explorer 8 and lower, the paste
and reset
events do not bubble. Such events are not supported for use with delegation, but they can be used when the event handler is directly attached to the element generating the event.
The error
event on the window
object uses nonstandard arguments and return value conventions, so it is not supported by jQuery. Instead, assign a handler function directly to the window.onerror
property.
The handler list for an element is set when the event is first delivered. Adding or removing event handlers on the current element won't take effect until the next time the event is handled. To prevent any further event handlers from executing on an element within an event handler, call event.stopImmediatePropagation()
. This behavior goes against the W3C events specification. To better understand this case, consider the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
In the code above, handler2
will be executed anyway the first time even if it's removed using .off(). However, the handler will not be executed the following times the click
event is triggered.
Examples:
Display a paragraph's text in an alert when it is clicked:
1 2 3 |
|
Pass data to the event handler, which is specified here by name:
1 2 3 4 |
|
Cancel a form submit action and prevent the event from bubbling up by returning false
:
1 |
|
Cancel only the default action by using .preventDefault()
.
1 2 3 |
|
Stop submit events from bubbling without preventing form submit, using .stopPropagation()
.
1 2 3 |
|
Pass data to the event handler using the second argument to .trigger()
1 2 3 4 |
|
Use the the second argument of .trigger()
to pass an array of data to the event handler
1 2 3 4 |
|
Attach and trigger custom (non-browser) events.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
|
Demo:
Attach multiple event handlers simultaneously using a plain object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
|
Demo:
Click any paragraph to add another after it. Note that .on()
allows a click event on any paragraph--even new ones--since the event is handled by the ever-present body element after it bubbles to there.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
|
Demo:
Display each paragraph's text in an alert box whenever it is clicked:
1 2 3 |
|
Cancel a link's default action using the .preventDefault()
method:
1 2 3 |
|
Attach multiple events—one on mouseenter
and one on mouseleave
to the same element:
1 2 3 |
|
FAQs
What are the parameters for live () method? ›
Parameter | Description |
---|---|
event | Required. Specifies one or more events to attach to the elements. Multiple event values are separated by space. Must be a valid event. |
data | Optional. Specifies additional data to pass along to the function |
function | Required. Specifies the function to run when the event occurs |
There is also $(document).on( "ready", handler ) , deprecated as of jQuery 1.8 and removed in jQuery 3.0. Note that if the DOM becomes ready before this event is attached, the handler will not be executed.
What does .on do in JavaScript? ›The on() method attaches one or more event handlers for the selected elements and child elements. As of jQuery version 1.7, the on() method is the new replacement for the bind(), live() and delegate() methods.
What is the importance of $( document ready () in jQuery? ›$( document ). ready()
A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ). ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.
In short: . bind() will only apply to the items you currently have selected in your jQuery object. . live() will apply to all current matching elements, as well as any you might add in the future.
What is the difference between event bubbling and event capturing? ›Event Capturing is opposite to event bubbling, where in event capturing, an event moves from the outermost element to the target. Otherwise, in case of event bubbling, the event movement begins from the target to the outermost element in the file.
Why should you never use document write () after the document is loaded? ›If the script then dynamically injects another script, the browser is forced to wait even longer for the resource to download. Using document. write() can drastically increase blocking time, latency, and overall page loading times (especially, on slower internet connections).
Is $( document .ready necessary? ›no. if you've placed all your scripts right before the </body> closing tag, you've done the exact same thing. Additionally, if the script doesn't need to access the DOM, it won't matter where it's loaded beyond possible dependencies on other scripts.
What is the difference between on document load and ready? ›The key difference between $(document). ready() and $(window). load() event is that the code included inside onload function will run once the entire page(images, iframes, stylesheets,etc) are loaded whereas the $(document). ready() event fires before all images,iframes etc.
Can you use for in on arrays? ›In isolation, there is nothing wrong with using for-in on arrays. For-in iterates over the property names of an object, and in the case of an "out-of-the-box" array, the properties corresponds to the array indexes.
Why is JavaScript so hard? ›
JavaScript is so hard to learn because it's an asynchronous programming language. It's also single-threaded, which means it uses its asynchronous nature in a radically different way than most other programming languages.
What is the difference between event emitter once and on? ›When a listener is registered using the eventEmitter.on() method, that listener is invoked every time the named event is emitted. Using the eventEmitter.once() method, it is possible to register a listener that is called at most once for a particular event.
What is the purpose of document write () method? ›The document. write() method writes a string of text to a document stream opened by document.
Can I use document ready multiple times? ›Yes we can do it as like I did in below example both the $(document). ready will get called, first come first served.
What is $( document ready () equivalent in JavaScript? ›ready() equivalent in JavaScript? In jQuery, if you want an event to work on your page, you should call it inside the $(document). ready() function. Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded.
What is bind () used for? ›bind() The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
What is bind () method in JavaScript? ›bind is a method on the prototype of all functions in JavaScript. It allows you to create a new function from an existing function, change the new function's this context, and provide any arguments you want the new function to be called with.
What is the difference between bind and on? ›on() method is the preferred method for attaching event handlers to a document. For earlier versions, the . bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .
What are the 3 types of events? ›What are the classifications of event types? Event types can be separated into corporate, private, or charity. Corporate events focus on businesses and customers, whereas private events are more recreational and charity events are for philanthropy.
Which method stops event bubbling? ›stopPropagation() method stops the bubbling of an event to parent elements, preventing any parent event handlers from being executed.
What is the difference between preventDefault and stopPropagation? ›
preventDefault() will not allow the user to leave the page and open the URL. The event. stopPropagation() method stops the propagation of an event from occurring in the bubbling or capturing phase. The event on a href element id=”child” stop propagation to parent elements from a child.
Why we shouldn't use document write ()? ›. write is considered a browser violation as it halts the parser from rendering the page. The parser receives the message that the document is being modified; hence, it gets blocked until JS has completed its process.
Where does document write () produce its output? ›The write() method writes directly to an open (HTML) document stream.
Does document write overwrites entire page? ›write after the document has loaded, it overwrites the entire document. If it is run before that, it does not overwrite it.
Why document ready is deprecated? ›In jQuery 3.0, all other syntax methods except $(handler); are deprecated. The official justification is: This is because the selection has no bearing on the behavior of the . ready() method, which is inefficient and can lead to incorrect assumptions about the method's behavior.
What can be used instead of document ready? ›Answer: Use the DOMContentLoaded Event
You can utilize the JavaScript Window's DOMContentLoaded event to construct $(document). ready() equivalent without jQuery.
ready() is called after the DOM has been initialized, the new handler passed in will be executed immediately. The . ready() method can only be called on a jQuery object matching the current document, so the selector can be omitted.
When should you use document ready? ›The ready() method is used to make a function available after the document is loaded. Whatever code you write inside the $(document ). ready() method will run once the page DOM is ready to execute JavaScript code.
Which loads first document ready or window load? ›ready function event executes a bit earlier than window. onload and is called once the DOM(Document object model) is loaded on your page. It will not wait for the images, frames to get fully load.
What does document ready do? ›The document ready event signals that the DOM of the page is now ready, so you can manipulate it without worrying that parts of the DOM has not yet been created. The document ready event fires before all images etc. are loaded, but after the whole DOM itself is ready.
How do you use an on? ›
ON Use on when something is touching the surface of something. It could be a horizontal surface, like a floor or beach, or a vertical surface, like a wall (“They hung pictures ON the wall”). We also use “on” for the surfaces of body parts (“He has a tattoo ON his arm”).
Can you use for of on a string? ›The for..of loop in JavaScript allows you to iterate over iterable objects (arrays, sets, maps, strings etc).
Does Size () work on arrays? ›Unlike the String and ArrayList, Java arrays do not have a size() or length() method, only a length property.
Can I learn JavaScript in 2 months? ›However, unlike CSS and HTML, JavaScript is not something that can be aced in just two weeks. But, it can be done in just three months! Most employers will be happy to hire you as their web developers if you just master some of the JavaScript basics. Of course, learning never stops.
What is the hardest programming language? ›- C++ C++ is an object-oriented programming language and is considered the fastest language out there. ...
- Prolog. Prolog stands for Logic Programming. ...
- LISP. LISP stands for List Processing. ...
- Haskell. ...
- Assembly Language (ASM) ...
- Rust. ...
- Esoteric Languages.
Asynchronous JavaScript (promises, callbacks, async/await) Closures. The event loop. Recursion.
Can an element have two event listeners? ›The addEventListener() method
You can add many event handlers to one element. You can add many event handlers of the same type to one element, i.e two "click" events. You can add event listeners to any DOM object not only HTML elements.
Conclusion. Use Eventemitter when transferring data from child component to parent component. Use Subject to transfer data from one component to another component.
Do event listeners only work once? ›This is why the third options parameter to addEventListener has a property called once that when set to true will ensure your event listener only runs one time. No matter how many times I click the above button it will only log Clicked one time since the event listener automatically removes itself after running once.
What is the difference between window alert () and document write () method? ›document. write modifies what user sees in the browser by adding additional content to DOM. Alerts are used to alert end users who access the web page.
What is the difference between document write () and window prompt ()? ›
Prompt is a higher "priority" in a way than document. write() because prompt() is used if you want the user to input a value before entering a page.
What are the 3 possible purposes for writing your document? ›The three main purposes for writing are to persuade, inform, and entertain. In persuasive writing, the author works to convince the reader to do something or to believe in an idea. In informative writing, the author is writing in order to inform the reader about a topic.
Is used to create multiple documents at once answer? ›Mail Merge is a handy feature that incorporates data from both Microsoft Word and Microsoft Excel and allows you to create multiple documents at once, such as letters, saving you the time and effort of retyping the same letter over and over.
What is the difference between find and children methods? ›children() method differs from . find() in that . children() only travels a single level down the DOM tree while . find() can traverse down multiple levels to select descendant elements (grandchildren, etc.)
What is the difference between $( function () and $( document .ready in jQuery? ›So technically they are both the same. Not major difference between these two declaration. They used based on weather you use JavaScript then you should use $(document). ready declaration in other case you use jQuery library which is a part of JavaScript then you should use $(function) declaration.
What can I use instead of document getElementById? ›A commonly-used alternative to document. getElementById is using a jQuery selector which you read about more here.
What is the difference between DOM content loaded and document ready? ›ready() method differs in an important and useful way: If the DOM becomes ready and the browser fires DOMContentLoaded before the code calls . ready( handler ), the function handler will still be executed. In contrast, a DOMContentLoaded event listener added after the event fires is never executed.
What can I use instead of document ready in JavaScript? ›Answer: Use the DOMContentLoaded Event
You can utilize the JavaScript Window's DOMContentLoaded event to construct $(document). ready() equivalent without jQuery.
all. Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes.
Is document ready JavaScript or jQuery? ›jQuery $(document). ready() is a basic part of using jQuery. The jQuery document ready function executes when the DOM (Document Object Model) is completely loaded in the browser. jQuery document ready is used to initialize jQuery/JavaScript code after the DOM is ready, and is used most times when working with jQuery.
What is document write () in JavaScript? ›
write in JavaScript is a function that is used to display some strings in the output of HTML web pages (Browser window).
Which of the following is an equivalent replacement of document ready? ›Explanation: The equivalent replacement of $(document). ready(f) is $(f). Writing $(document) performs the function of selecting the whole document which is the same as writing $() only.
Can I still use deprecated API? ›A deprecated API is one that you are no longer recommended to use, due to changes in the API. While deprecated classes, methods, and fields are still implemented, they may be removed in future implementations, so you should not use them in new code, and if possible rewrite old code not to use them.
Do deprecated methods still work? ›A deprecated class or method is like that. It is no longer important. It is so unimportant, in fact, that you should no longer use it since it has been superseded and may cease to exist in the future.
Can I still use deprecated? ›It means that it is bad practice to use it. It can still be used, but eventually it will not work with other things because it is no longer being supported. Best practice is to use the requested alternative to any depreciated type.
What is the difference between window onload and document ready? ›ready() is a jQuery event which occurs when the HTML document has been fully loaded, while the window. onload event occurs later, when everything including images on the page loaded. Also window. onload is a pure javascript event in the DOM, while the $(document).
Why is document write () not recommended anymore? ›Document write () is defined as a command that writes code on a document with HTML or Javascript. However, this is not recommended as it delays the loading of basic home page content.
Do people still use jQuery? ›How Popular Is jQuery? StackOverflow's 2022 survey of web technologies used by professional developers found that just over 29% of more than 45,000 respondents were working with jQuery. Among the JavaScript libraries, jQuery was second only to React.
What is the difference between prop () and attr ()? ›prop() method provides a way to explicitly retrieve property values, while . attr() retrieves attributes. For example, selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, and defaultSelected should be retrieved and set with the . prop() method.