Input type text of the event. Form events. Creating a custom event
The input event fires when the value of an element is used to create interactive controls for web-based forms in order to accept data from the user; a wide variety of types of input data and control widgets are available, depending on the device and user agent. "\u003e , element represents a control that provides a menu of options "\u003e
Bubbles | Yes |
---|---|
Cancelable | # |
Interface | InputEvent |
Event handler property | GlobalEventHandlers.oninput |
Html
JavaScript
const input \u003d document.querySelector ("input"); const log \u003d document.getElementById ("values"); input.addEventListener ("input", updateValue); function updateValue (e) (log.textContent \u003d e.target.value;)Result
Specifications
Specification | Status |
---|---|
HTML Living Standard |
Living Standard |
Document Object Model (DOM) Level 3 Events Specification The definition of "input event" in that specification. |
Obsolete |
Browser compatibility
The compatibility table in this page is generated from structured data. If you "d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
Update compatibility data on GitHub
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | Android webview | Chrome for Android | Firefox for Android | Opera for Android | Safari on iOS | Samsung Internet | |
input event | Chrome Full support Yes | Edge Full support 79 Full support 79 No support 12 - 79 Notes Notes Not supported on select, checkbox, or radio inputs. | Firefox Full support Yes | IE Partial support 9 |
In the last topic, we looked at keystroke events. In this topic, we'll look at other form events. Including sending the form to the server.
Element in focus
When a form element is in focus, a focus event fires, and when the element goes out of focus, a blur event fires. Let's create an input field and output text to the console when it receives focus and when it exits focus:
HTML code:
There is no point in using these events to change the style of an element. For this, there is a focus pseudo-class in CSS.
Entering a value
Input event occurs when the user types text into an input field. It fires when each character is added or removed, and when text is copied into an input field. In some browsers, it works in an unusual way: each time you enter a character, a blur event is raised, then the input event handler is executed, and then the focus event is raised. If there are no focus and blur event handlers, then this is not a problem. But if they are, then they will be triggered every time a character is added.
Add one more tag to the page and display its value when entering text:
HTML code:
JavaScript:
28 |
var newv \u003d document.getElementById ("new_value"); newv.onchange \u003d function () (console.log ("Value changed to:" + newv.value);); |
Form submission
The submit event fires when the form is submitted to the server. It is used to validate the data that the user has entered into the form. The handler checks the values \u200b\u200bof the form elements, and if some values \u200b\u200bare entered incorrectly, the form submission is canceled. This usually displays a message indicating what needs to be fixed.
Place the created tags to the form and add a button to submit the form:
HTML code:
In the previous examples, the form elements were already found, so the handler is not searched again.
If the form is filled out correctly, that is, all fields have at least two characters, then the browser will try to run the file specified in the action attribute, and an error will occur, because there is no such file. But there is no risk in this, so there is no need to be afraid of checking the operation of the script. If less than two characters are entered in one of the fields, a message will appear and the sending will be canceled. If there are a lot of checks, then you can display your message for each check and cancel the form submission.
In this article, we'll look at the methods that the jQuery library provides a web developer for handling events.
The browser provides an API (for example, the addEventListener function) to work with events in JavaScript. Using this function, you can specify the code to be executed when the browser fires the specified event for the specified element.
Handling events with jQuery methods
On function syntaxBefore proceeding to add event handler elements, these elements must first be retrieved. To find out how to find the elements you want on a page, see jQuery - Selecting Elements.
In jQuery, you can hang an event (event listener) on a specific element using the on and one functions, as well as short on entries.
// function on .on (events, handler); // function one .one (events, handler); // events - an event or a list of events separated by a space, upon the occurrence of which it is necessary to execute a handler // handler - a function (an event handler) // short record of the function on .event (handler); // event - the name of the event (can be used to handle only those events for which jQuery has such a short notation)
The one function differs from on only in that it executes the handler only once when the specified event occurs.
For example, let's use the on function to add a click event for all elements with the btn class:
// using the anonymous function as a handler $ (". btn"). on ("click", function () (// actions that will be performed when an event occurs ... console.log ($ (this) .text ( ));)); // using a regular function as a handler var myFunction \u003d function () (console.log ($ (this) .text ());) $ (". btn"). on ("click", myFunction);
The above code, written using the on function shorthand:
$ (". btn"). click (function () (// actions to be performed when an event occurs ... console.log ($ (this) .text ());));
Additional information about the event
While handling the event, you can find out some additional information about him. Passing this information, namely the Event object, to the event handler is always done through the first argument.
$ ("# demo"). on ("click", function (e) (// e - an Event object containing additional information about the event that occurred // frequently used properties of the Event object e.preventDefault (); // cancel the action by default e.stopPropagation (); // stop further bubbling of the event // e.type - get the type of the event // e.target - link to the element on which the event occurred // e.currentTarget - link to the current element (for which handler triggered) This property is usually equal to the this function. // e.currentTarget \u003d\u003d\u003d this // e.which - key code (for mouse), button or symbol code (for keyboard) //e.pageX, e.pageY - coordinates of the cursor, relative to the left top corner document));
Namespace
In jQuery, after specifying an event name, you can optionally specify a namespace.
For instance:
// namespace click event first $ ("# demo"). on ("click.first", function () (console.log ("1 click event handler");)); // namespace click event second $ ("# demo"). on ("click.second", function () (console.log ("2 click event handler");));
The namespace is a very handy thing. It is used, for example, when you need to call not all events, but only with a specific name.
// trigger a click event in the namespace first $ ("# demo"). trigger ("click.first"); // trigger a click event in the namespace second $ ("# demo"). trigger ("click.second");
It is also very easy to delete certain events with it:
// remove handlers for the click event in the namespace first $ ("# demo"). off ("click.first"); // remove the click event handlers in the namespace second $ ("# demo"). off ("click.second");
Descriptions and examples of using the trigger and off functions are discussed in the article a little below.
Passing additional data to the handler
If necessary, you can pass data to the event handler (by specifying an additional argument in the on function). The passed data is accessed within the handler through the Event object.
This is done like this (example):
...
How to hang multiple events on one element
An example of using one handler for several (2 or more) events:
$ ("# id"). on ("keyup keypress blur change", function (e) (console.log (e.type); // event type)); // or so var myFunction \u003d function () (...) $ ("# id") .keyup (myFunction) .keypress (myFunction) .blur (myFunction) .change (myFunction);
Each event has its own function:
$ ("# id"). on ((mouseenter: function () (// mouseenter event handler ...), mouseleave: function () (// mouseleave event handler ...), click: function () (/ / click event handler ...)));
An example of using several handlers (functions) for one event in jQuery:
$ ("# demo"). click (function () (console.log ("1 click event handler");)); $ ("# demo"). click (function () (console.log ("2 click event handler");));
For example, you can find out in what order the events will be executed as follows:
Var eventList \u003d $ ._ data ($ ("# demo"), "events"); console.log (eventList);
Calling an event programmatically
There are 2 methods in jQuery to call an event from code:
- trigger - triggers the specified event on the element.
- triggerHandler - Calls an event handler without actually firing the event.
jQuery - Page load event (ready)
The process of adding an event handler to some element usually occurs after the page has loaded, i.e. when the DOM document tree is already built. Otherwise, when writing handlers, you can refer to elements that are not yet on the page.
The shortest jQuery page load event entry looks like this:
$ (function () (// actions to be performed after loading the document ...));
But, you can use a longer record:
$ (document) .ready (function () (// actions to be performed after loading the document ...));
jQuery - Load Event
The browser generates a load event for an element when it and all its nested elements have been fully loaded. This event is only for elements that contain a URL: image, script, iframe and window.
For example, execute the function when the page is fully loaded (including images):
$ (window) .on ("load", function () (// actions after the page is fully loaded ...));
For example, let's print a message to the console when the specified image is loaded:
...
jQuery - Mouse Events
The most commonly used events in jQuery to track mouse actions are:
- mousedown
- mouseup
- click
- mousemove
- wheel
- hover
- mouseenter
- mouseover
- mouseleave
- mouseout
jQuery - Click Event
The click event is a complex event, it fires after the mousedown and mouseup events have been raised. The mousedown event occurs when the pointer is over an element and the mouse button is pressed. The mouseup event occurs when the pointer is over an element and the mouse button is released. The click event is generated when the cursor is over an element and the mouse button is pressed and released. These events can receive any HTML elements.
For example, let's hang a handler on the onclick event of the window element. When this event occurs, the handler will display the number of the pressed key and the coordinates of the cursor:
$ (window) .on ("click", function (e) (// handle the click event ... console.log ("Button clicked:" + e.which); // 1 - left button, 2 - middle button, 3 - right one console.log ("Cursor coordinates: x \u003d" + e.pageX + "; y \u003d" + e.pageY); ));
For example, let's hang the onclick event on all elements with the btn class:
$ (". btn"). on ("click", function () (// code of the button click event handler ...)); Brief record of event on click: $ (". Btn"). Click (function () (...));
For example, let's see how you can hide a block some time after the click event:
...
jQuery - Event on hover
jQuery - What is a hover event
The hover event is complex and consists of 2 events:
- occurrences (mouseenter, mouseover);
- leaving (mouseleave, mouseout).
The mouseenter and mouseleave events in jQuery differ from mouseover and mouseout only in that they do not fire when the cursor enters and leaves the inner elements of the element being listened to, respectively. In other words, the mouseover and mouseout events bubble up, but the mouseenter and mouseleave events do not.
For example, let's change the color of a list item when the cursor is hovered over it:
- A pen
- Pencil
- Ruler
The same steps, but using mouseover and mouseout:
$ ("ul\u003e li"). mouseover (function () (// when entering an element $ (this) .css ("color", "orange");)). mouseout (function () (// when leaving the element $ (this) .css ("color", "black");));
These methods do not need to be used together; they can also be used separately.
For example, let's count the number of visits to an element when the mouse hover event occurs:
Instead of using mouseenter and mouseleave, the hover event can be used.
For example, let's rewrite the above example using hover:
$ ("ul\u003e li"). hover (function () (// when entering an element $ (this) .css ("color", "orange");), function () (// when leaving an element $ ( this) .css ("color", "black");));
When using the hover event in jQuery, the first handler is used to set actions when the cursor enters the element (mouseenter), and the second when it leaves (mouseleave).
If you specify a single handler for the hover event, then it will be executed both for handling mouse hovering and for leaving it.
For instance:
$ ("h1"). hover (function () (console.log ("An element entry or exit event occurred");));
jQuery - Mouse Movement Event
The mousemove event is dispatched to an element when the mouse pointer moves within it. Any HTML element can receive this event.
$ (". target"). mousemove (function (e) (console.log ("A handler for the mousemove event was called."); console.log ("Coordinates relative to the top-left corner of the document:" + e.pageX + "," + e.pageY); console.log ("Coordinates of the cursor inside the target:" + e.offsetX + "," + e.offsetY);));
jQuery - Mouse Wheel Event
Listening to the scroll event of the mouse wheel can be done like this:
$ (window) .on ("wheel", function (e) (// handler code (for example) ... console.log ("Number of pixels scrolled:" + e.originalEvent.deltaY); if (e.originalEvent. deltaY< 0){ console.log("Прокручиваем вверх"); } else { console.log("Прокручиваем вниз"); } });
This event, unlike scroll, is generated by the browser only for the mouse wheel, and it does not matter whether the element is scrolled or not, i.e. you can work with it on elements with overflow equal to hidden. Another difference is that wheel is generated before scrolling, and scroll is generated after it.
jQuery - Keyboard Events
When a keyboard key is pressed, the browser generates events in the following order:
Keydown -\u003e keypress -\u003e keyup
- keydown (key pressed but not released yet);
- keypress (the event is generated for letters, numbers and other keys, except for control keys) - designed to get the character code (the keydown and keyup events allow you to find out only about the key code, but not the character);
- keyup (generated by the browser when a key is released).
For example, let's write a handler to listen for all events that occur when a key is pressed:
...
An example that shows how you can listen for the keypress event and see if the specified key combination is pressed:
$ (document) .keypress ("c", function (e) (if (e.ctrlKey) (console.log ("Ctrl + c keys pressed");)));
An example of how you can listen to the Ctrl + Enter key combination:
$ (document) .keydown (function (e) (// with macOS X support if ((e.ctrlKey || e.metaKey) && (e.keyCode \u003d\u003d 13 || e.keyCode \u003d\u003d 10)) (/ / your actions... ) )
Example, using keydown and keyup events:
...
jQuery - Form Element Events
In jQuery, the following events can be distinguished for form elements and more:
- focus (focusin)
- blur (focusout)
- change
- input (for text form elements)
- select
- submit
jQuery - Focus Gain and Loss Events
A focus event is dispatched to an element when it receives focus. This event fires for input, select and link elements (a href \u003d "..."), as well as any other elements that have the tabindex property set. An element usually gains focus by clicking or pressing the Tab key on the keyboard. The focus event does not bubble up.
In addition to focus, there is also a similar event called focusin. Unlike focus this event pops up and it can, for example, be used to detect focus events by parent elements.
The blur event is sent to an element when it loses focus. Like focus, blur has a similar focusout event. This event differs from blur in that it can bubble. This feature can be used, for example, to get it on parent elements, and not just on the element that called it (target).
For example, when a div element receives a focus event, set its background to orange:
...
Exactly the same cannot be done using the focus and blur events, since they don't pop up:
$ ("# demo input"). focus (function () ($ (this) .parent (). css ("background-color", "orange");)) .blur (function () ($ (this) .parent (). css ("background -color "," inherit ");));
jQuery - Change Event
The change event is intended to register a change in the value of the input, textarea and select elements. For select, checkboxes, and radio buttons, this event occurs immediately (i.e., as soon as the user makes a choice). But for other elements, this event will not occur until that element loses focus.
An example of using the change event to track the state of a checkbox element. The availability of the button will be determined depending on what state (checked or not) the checkbox is in:
...
An example showing how to get the value of a select element when it changes:
...
An example showing how to get all the selected elements of a select when it changes:
...
An example of programmatically raising the change event on a select element:
// list - id of the change element $ ("# list"). trigger ("change"); // short note $ ("# list"). change (); // call only the event handler change $ ("# list"). triggerHandler ("change");
An example of using the change event to get the value of an input element:
...
But besides the change event, there is also an input event for text elements. This event, unlike change, is generated immediately, and not after this element loses focus.
An example, using an input event to get the value of an input element:
$ ("input"). on ("input", function () (var value \u003d $ (this) .val (); console.log (value);));
An example showing one way to get the value of a textarea element:
...
An example that shows how to use the change event to get the value of the selected input element with type equal to radio:
Windows Linux macOS ...
jQuery - Select Event
The select event is generated by the browser when the user, inside input elements with type \u003d "text" or textarea, selects text.
$ ("# target"). select (function () (console.log ("Select event handler called");));
jQuery - Form submit event
The submit event is raised on an element when the user tries to submit a form. This event can only be added to form elements.
Example, using the submit event:
...
A programmatic call to submit the form:
$ ("# feedback"). submit (); $ ("# feedback"). trigger ("submit");
jQuery - Scroll Event
JQuery uses the scroll event to keep track of the scroll state.
For example, let's hang on the page scroll event a function that will display an element with the scrollup class if the scroll value is greater than 200px and hide it if the scroll value is less than this value.
// shorthand record of the function $ (window) .scroll (function () (// actions when scrolling the page ... if ($ (this) .scrollTop ()\u003e 200) ($ (". scrollup"). fadeIn () ;) else ($ (". scrollup"). fadeOut ();)));
jQuery - Resize Event
To listen for the browser window change event, use resize:
For example, let's create a handler that will display the width and height of the page at the end of the page when the browser window changes:
$ (window) .resize (function () ($ ("body"). append ("
Width x Height \u003d "+ window.innerWidth +" x "+ window.innerHeight +"
"); });jQuery - Canceling standard event behavior
Some elements in HTML have standard behavior. For example, when a user clicks on a link, he goes to the address specified in the href attribute. If you do not need this action, you can undo it. To cancel the standard behavior, call the preventDefault method of the event object in the event handler.
For example, let's cancel the standard behavior of all links on the page that have the service class:
$ ("a.service"). on ("click", function (e) (// cancel the default browser action e.preventDefault (); // actions that the link will perform ...));
What is surfacing and how to stop it
In addition to canceling a standard action, there is also such a thing as bubbling in the event mechanism. It lies in the fact that when the browser generates an event, it does it not only for the current element (target), but also for all its descendants, including the parent:
Current element (target) -\u003e parent of target -\u003e grandparent -\u003e ... -\u003e document -\u003e window
There are scenarios in jQuery when, in the presented chain, some element also has a handler for this event, which does not need to be executed. And so that this event does not spread to this element, it must be stopped. To do this, call the stopPropagation method of the event object in the handler of the desired element. After calling this method, the event will stop and will not bubble up.
For example, it is necessary that when the cursor is placed over an element with the mark class, its content turns orange.
In this case, if you do not specify the stopPropagation method, then when you move the cursor to a span element with the mark class, this event will occur not only for it, but for all of its parent elements. And this in this example will lead to the fact that the color of not only the text enclosed in the span will change, but also the entire paragraph.
If you need to override the default browser behavior and stop the event bubbling, then in jQuery, instead of calling these two methods, you can simply return false as the function result.
$ ("a"). on ("click", function (e) (//e.preventDefault (); //e.stopPropagation (); ... return false;));
Adding Events to Dynamically Created Objects
In order to hang an event on an element that does not yet exist, you can use the following on function construction:
$ (document) .on (eventName, selector, handler); // document or any other existing parent element // eventName is the name of the event // selector is a selector that filters children for which an event handler should be started // handler is an event handler
This action can be carried out due to the fact that the event floats, and, therefore, occurs in all ancestors of this element. And the object to which all events on the page are floated is document. Therefore, in most cases, it is he who is chosen. After that, knowing the selector, the on function can programmatically select among the elements (the element that caused this event (target) and all its ancestors, including the parent) those that match it. And then for all the selected elements, execute the handler specified in the on function. Actions by which event handling is transferred to another element (ancestor) are called in jQuery else event delegation process.
For example, let's add an event to an element that is not yet on the page:
Delegation can be used not only to handle events of dynamically created objects, but also in order not to bind a handler to each element (if there can be a lot of them on the page).
For example, we prohibit in the comments to go to external links (we will redirect such actions to the away page):
$ (document) .on ("click", "# comment a", function (e) (if (! (location.hostname \u003d\u003d\u003d this.hostname ||! this.hostname.length)) (e.preventDefault ( ); location.href \u003d "away? link \u003d" + encodeURIComponent ($ (this) .attr ("href"));)));
jQuery - Remove Event Handler
Event handlers are removed using the off method. At the same time, using it, you can remove only those handlers that were added through the on method.
Calling the off method without arguments will remove all event handlers added to the specified elements from the specified elements.
For example, let's disable all handlers for elements with the link class:
$ (". link"). off ();
For example, let's remove the click event for all elements with the link class:
$ (". link"). off ("link");
A special selector (**) allows you to remove only delegated events while keeping non-delegated ones:
$ (". link"). off ("click", "**");
Remove only specified delegated events (using a selector):
// add a delegated event $ ("ul"). on ("click", "li", function () (// display the content of the li element console.log ($ (this) .text ());)) ; // remove delegated event $ ("ul"). off ("click", "li");
Remove all openModal handlers for the delegated click event in the modal namespace for elements with class show:
$ ("body"). on ("click.modal", ".show", openModal);
Creating a custom event
JQuery uses the on and trigger methods to create custom events.
Let's look at the principle of creating a custom jQuery event using the following example: