Input events. Form events. jQuery - Mouse Move Event

In this article, we'll look at the methods that the jQuery library provides to the web developer for handling events.

To work with events in JavaScript scripts, the browser provides an API (for example, the addEventListener function). Using this function, you can specify code to be executed when the browser for a specified element generates a specified event.

Handling events using jQuery methods on function syntax

Before you can add event handlers to elements, you first need to obtain those elements. You can learn how to find the elements you need on a page in the jQuery article - Selecting Elements.

In jQuery, hang an event (event listener) on specific element you can use the on and one functions, as well as the on shorthand notation.

// 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) // handler - a function (event handler) // a short description of the function on .event(handler); // event - the name of the event (can be used to process only those events for which such a short entry has been created in jQuery)

The one function differs from on only in that it executes the handler only once when the specified event occurs.

For example, use the on function to add a click event for all elements with the btn class:

// use an anonymous function as a handler $(".btn").on("click", function() ( // actions that will be performed when the event occurs... console.log($(this).text( )); )); // usage regular function as a handler var myFunction = function() ( console.log($(this).text()); ) $(".btn").on("click", myFunction);

The above code, written using the on function shorthand:

$(".btn").click(function() ( // actions that will be performed when the event occurs... console.log($(this).text()); ));

Additional information about the event

When you process an event, you can find out some additional information about it. The transfer of this information, namely the Event object, to the event handler is always carried out through the first argument.

$("#demo").on("click", function(e)( // e is 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 event bubbling // e.type – get the event type // e.target – link to the element on which the event occurred // e.currentTarget – link to the current element (for which the handler was triggered). This property is usually equal to the this function. // e.currentTarget === this // e.which – key code (for a mouse), button or symbol code (for a keyboard) //e.pageX, e.pageY – cursor coordinates relative to the upper left corner of the document));

Namespace

In jQuery, after specifying the event name, you can additionally specify a namespace.

For example:

// click event in namespace first $("#demo").on("click.first",function())( console.log("1 click event handler"); )); // click event in the second namespace $("#demo").on("click.second",function())( console.log("2 click event handler"); ));

Namespaces are a very convenient thing. It is used, for example, when you need to trigger not all events, but only those with a specific name.

// trigger the click event in the first namespace $("#demo").trigger("click.first"); // trigger the click event in the second namespace $("#demo").trigger("click.second");

It also makes it very easy to delete certain events:

//remove click event handlers in the first namespace $("#demo").off("click.first"); //remove click event handlers in the second namespace $("#demo").off("click.second");

Descriptions and examples of using the trigger and off functions are discussed in the article a little lower.

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 inside the handler is accessed through the Event object.

This is done like this (example):

Show content 1 Show content 2 ... $("#showContent1").on("click", (title:"Title 1", content: "Content 1..."), function(e)( var output = ""+e.data.title+": " + e.data.content; $("#content").html(output); )); $("#showContent2").on("click", (title:"Title 2", content: "Content 2..."), function(e)( var output = ""+e.data.title+" : " + e.data.content; $("#content").html(output); ));

How to attach multiple events to 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 = 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 events will be executed like this:

Var eventList = $._data($("#demo"), "events"); console.log(eventList);

Calling an Event Programmatically

There are 2 methods to call an event from code in jQuery:

  • trigger - triggers the specified event on an element.
  • triggerHandler - calls an event handler, but the event itself does not occur.
$("#header").on("click", function() ( console("The #header element was clicked"); ) )); // programmatic call of the element's click event $("#header").trigger("click"); // short version of this call $("#header").click(); // calling the click event handler for the selected element $("#header").triggerHandler("click"); jQuery - Page load event (ready)

The process of adding an event handler to an element is usually done after the page has loaded, i.e. when the DOM tree of the document has already been built. Otherwise, when writing handlers, you may access elements that are not yet on the page.

The shortest entry for a page load event in jQuery looks like this:

$(function())( // actions to be performed after loading the document... ));

But you can also use a longer notation:

$(document).ready(function())( // actions that need to be performed after loading the document... ));

jQuery - Load event (load)

The browser generates a load event on an element when it and all its nested elements have been fully loaded. This event is only intended for elements that contain a URL: image , script , iframe and window .

For example, execute a function when the page is completely loaded (including images):

$(window).on("load", function() ( // actions after the page is fully loaded... ));

For example, let's display a message to the console when specified image will be loaded:

... $("#image").on("load", function() ( console.log("Image 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 occurs after the mousedown and mouseup events have been fired. 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 fired when the cursor is over an element and the mouse key is pressed and released. These events can be received by any HTML element s.

For example, let's attach a handler to the onclick event of the window element. When this event occurs, the handler will display the number of the key pressed and the coordinates of the cursor:

$(window).on("click", function(e) ( // handle the click event... console.log("Button pressed: " + e.which); //1 - left button, 2 - middle button , 3 - right console.log("Cursor coordinates: x = " + e.pageX + " ; y = " + e.pageY); ));

For example, let's attach the onclick event to all elements with the btn class:

$(".btn").on("click", function())( // code for the button click event handler... )); A short description of the click event: $(".btn").click(function())( ... ));

For example, let's look at how you can hide a block some time after the click event:

...Hide the block after 5 seconds... ... $(".hide-message").click(function(e)( e.preventDefault(); var _this = this; setTimeout(function())( $( _this).closest(".message").hide(); ), 5000); ));

jQuery - Hover event
jQuery - What is the hover event

The event when the cursor is brought up 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 occur when the cursor respectively enters and leaves the internal elements of the listened element. 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 you move the cursor to it:

  • Pen
  • Pencil
  • Ruler
... $("ul>li"). mouseenter(function())( // when entering an element $(this).css("color","orange"); )). mouseleave(function())( // when leaving the element $(this).css("color","black"); ));

The same actions, but using mouseover and mouseout:

$("ul>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 have to be used together; they can also be used separately.

For example, let's count the number of visits to an element when the Hover event occurs:

Count: 0 ... $("#count").mouseenter(function())( var count = parseInt($(this).find("span").text()); count++; $(this).find ("span").text(count); ));

Instead of using mouseenter and mouseleave, you can use the hover event.

For example, let's rewrite the above example using hover:

$("ul>li").hover(function())( // when entering the element $(this).css("color","orange"); ), function())( // when leaving the element $( this).css("color","black"); ));

When using the hover event in jQuery, the first handler is used to set the action when the cursor enters an element (mouseenter), and the second handler is used when leaving it (mouseleave).

If you specify one handler for the hover event, it will be executed both to handle mouse hover and mouse leave.

For example:

$("h1").hover(function())( console.log("Element entry or exit events occurred"); ));

jQuery - Mouse Move Event

The mousemove event is sent to an element when the mouse pointer moves within it. Any HTML element can receive this event.

$(".target").mousemove(function(e) ( console.log("Handler for mousemove event called."); console.log("Coordinates relative to the upper left corner of the document: " + e.pageX + ", " + e.pageY); console.log("Cursor coordinates inside the target: " + e.offsetX + ", " + e.offsetY); ));

jQuery - Mouse wheel event

Listening to the mouse wheel scroll event 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. it can be used 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 -> keypress -> keyup

  • keydown (key pressed but not released yet);
  • keypress (the event is generated for letters, numbers and other keys, with the exception of control ones) – intended to obtain the code of a character (the keydown and keyup events allow you to find out only about the code of a key, but not a character);
  • keyup (generated by the browser when the key is released).

For example, let's write a handler to listen to all events that occur when a key is pressed:

... $("#target").on("keydown keypress keyup", function(e) ( console.log("Event type: " + e.type); // keydown, keypress, keyup console.log( "The code of the pressed key or symbol: " + e.which); // the symbol code allows you to get only keypress console.log("The Alt key is pressed: " + e.altKey); console.log("The Ctrl key is pressed: " + e .ctrlKey); console.log("Shift key pressed: " + e.shiftKey); console.log("Cmd key pressed (osMac): " + e.metaKey); ));

An example that shows how you can listen to the keypress event and find out whether a specified key combination is pressed:

$(document).keypress("c", function(e) ( if(e.ctrlKey) ( console.log("Ctrl+c key combination pressed"); ) ));

An example of how you can listen to the Ctrl+Enter key combination:

$(document).keydown(function(e) ( // supports macOS X if ((e.ctrlKey || e.metaKey) && (e.keyCode == 13 || e.keyCode == 10)) ( / / your actions... ) )

Example using keydown and keyup events:

... $("#name"). keydown(function())( $(this).css("background-color", "yellow"); )). keyup(function())( $(this).css("background-color, "pink"); ));

jQuery - Form Element Events

In jQuery, you can highlight the following events for form elements and more:

  • focus (focus)
  • blur(focusout)
  • change
  • input (for text form elements)
  • select
  • submit
jQuery - Focus gain and loss events

The focus event is sent to an element when it receives focus. This event is generated for input , select , and link elements (a href="..."), as well as any other elements that have the tabindex property set. Gaining focus to an element is usually done by clicking or pressing the Tab key on the keyboard. The focus event doesn't bubble up.

In addition to focus, there is another similar event, it is called focusin. Unlike focus, this event bubbles and can, for example, be used to detect a focus event by parent elements.

The blur event is sent to an element when it loses focus. Just like focus , the blur event has a similar focusout event. This event differs from blur in that it can bubble. This feature can be used, for example, to receive 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:

... $("#demo"). focusin(function())( $(this).css("background-color","orange"); )) .focusout(function())( $(this).css("background-color","inherit") ; ));

It will not be possible to do exactly the same thing using the focus and blur events, because 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 designed to register a change in the value of the input , textarea , and select elements. For select elements, checkboxes, and radio buttons, this event occurs immediately (that is, as soon as the user makes a choice). But for other elements, this event will not occur until that element loses focus.

Usage example change events to monitor the state of the checkbox element. The availability of the button will be determined depending on the state (checked or not) of the checkbox:

Send... $(function() ( $("#agree").on("change", function())( if (this.checked) ( $("#send").prop("disabled",false ); ) else ( $("#send").prop("disabled",true); ) )); ));

An example in which we will look at how to get the value of a select element when it changes:

First value Second value Third value ... $(function() ( $("#list").on("change", function())( var value = $(this).val(); $("#result ").text(value); )); ));

An example in which we will look at how to get all selected elements of a select when it changes:

Green Red Blue Brown Purple Gray ... $("select") .change(function () ( var colors = ; $("select option:selected").each(function() ( colors.push($(this) .text()); )); console.log("Selected colors: " + colors.join()); )).change();

An example of programmatically calling the change event on a select element:

// list - id of the change element $("#list").trigger("change"); // shorthand $("#list").change(); // call only the change event handler $("#list").triggerHandler("change");

An example of using the change event to get the value of an input element:

... $(function() ( // input value change event (occurs only after losing focus) $("input").on("change", function())( var value = $(this).val() ; console.log(value); )); ));

But besides the change event, there is also an input event for text elements. This event, unlike change, is generated immediately, and not after the element loses focus.

An example of using an input event to get the value of an input element:

$("input").on("input",function())( var value = $(this).val(); console.log(value); ));

An example that shows one way to get the value of a textarea element:

... $("textarea").on("input",function())( var value = $(this).val(); console.log(value); ));

An example in which we will look at how to use the change event to get the value of the selected input element with type equal to radio:

Windows Linux macOS ... $(function() ( $("input").on("change", function())( var value = $(this).val(); console.log(value); )) ; ));

jQuery - Select event

The select event is generated by the browser when the user inside input elements with type="text" or textarea selects text.

$("#target").select(function() ( console.log("Select event handler called"); ));

jQuery – Form submission event (submit)

The submit event occurs on an element when the user attempts to submit a form. This event can only be added to form elements.

Example, usage submit events:

... ... $("#feedback").submit(function(e) ( // cancel submitting the form e.preventDefault(); // other actions, for example, to submit the form via ajax... ));

Programmatic call to submit a form:

$("#feedback").submit(); $("#feedback").trigger("submit");

jQuery - Scroll Event

jQuery uses the scroll event to track scroll state.

For example, let’s attach a function to the page scroll event 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.

// short description of the function $(window).scroll(function() ( // actions when scrolling the page... if ($(this).scrollTop()>200) ( $(".scrollup").fadeIn() ; ) else ( $(".scrollup").fadeOut(); ) ));

jQuery - Window resizing event (resize)

To listen to the browser window change event, use resize:

For example, let’s create a handler that, when the browser window changes, will display its width and height at the end of the page:

$(window).resize(function() ( $("body").append("

Width x Height = " + window.innerWidth + " x " + window.innerHeight + "

"); });

jQuery - Overriding default 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 cancel it. To override the default behavior, you must call the event object's preventDefault method 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 standard browser action e.preventDefault(); //actions that the link will perform... ));

What is surfacing and how to stop it

Except cancellation standard action, in the mechanism of events there is also such a concept as ascent. It lies in the fact that when the browser generates an event, it does so not only for the current element (target), but also for all its descendants including the parent:

Current element (target) -> parent element of target -> grandparent element -> ... -> document -> window

In jQuery, there are scenarios when some element in the presented chain also has a handler for this event, which does not need to be executed. And to prevent this event from spreading to this element, it must be stopped. To do this, in the handler of the desired element, you need to call the stopPropagation method of the event object. After calling this method, the event will stop and will not bubble up.

For example, it is necessary that when you move the cursor to an element with the mark class, its contents become orange.

Some text...fragment...continued... ... $(".mark").on("hover", function(e)( e.stopPropagation(); $(this).css ("color",orange); ), function(e)( e.stopPropagation(); $(this).css("color",black); ) ));

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 also for all 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 from bubbling, 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 attach an event to an element that does not yet exist, you can use the following construction of the on function:

$(document).on(eventName, selector, handler); // document or any other existing parent element // eventName - the name of the event // selector - a selector that filters the children for which the event handler needs to be launched // handler - the event handler

This action can be accomplished due to the fact that the event pops up, and therefore occurs in all the ancestors of this element. And the object to which all events on the page bubble up is document . Therefore, in most cases they choose it. After this, 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 selected elements, execute the handler specified in the on function. Actions through which event processing is transferred to another element (ancestor) is also called event delegation process in jQuery.

For example, let's add an event to an element that is not yet on the page:

Add a button // when you click on an element with id="addButton" add a new button to the top of the page $("#addButton").on("click", function(e) ( $("body").prepend("Delete me"); )); // add a click event that will be executed for elements that are not yet on the page $(document).on("click"".deleteMe", function() ( $(this).remove(); ));

Delegation can be used not only to process events of dynamically created objects, but also to avoid attaching a handler to each element (if there can be a lot of them on the page).

For example, we will prohibit following external links in comments (we will redirect such actions to the away page):

$(document).on("click","#comment a",function(e) ( if(!(location.hostname === this.hostname || !this.hostname.length)) ( e.preventDefault( ); location.href="away?link="+encodeURIComponent($(this).attr("href")); ) ));

jQuery - Remove event handler

Event handlers are removed using the off method. Moreover, it can be used to remove only those handlers that were added using the on method.

Calling the off method without arguments will remove any event handlers attached to 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 from all elements with the link class:

$(".link").off("link");

A special selector (**) allows you to delete only delegated events while preserving non-delegated ones:

$(".link").off("click","**");

Remove only the specified delegated events (using a selector):

// adding a delegated event $("ul").on("click","li", function())( // output the content of the li element to the console console.log($(this).text()); )) ; // removing the delegated event $("ul").off("click","li");

Remove all openModal delegated click event handlers in the modal namespace for elements with the show class:

$("body").on("click.modal", ".show", openModal);

Create a custom event

jQuery uses the on and trigger methods to create custom events.

Let's look at the principle of creating a special jQuery event using following example:

Call a custom event highlight (color green) Call a custom event highlight (color red) ... // add a custom event to all p elements that will change the color of the text and its content // receiving the data passed by the trigger method is done using the color arguments and title $(".module p").on("highlight", function(e, color, title) ( $(this).css("color",color); $(this).text("Called custom event highlight " +title); )); // when you click on an element with the success class, call the custom highlight event and pass parameters to it $(".success").click(function())( // using the second argument we will pass the data to the event handler $(this).closest(". module").find("p").trigger("highlight",["green","(green color)"]); )); // when you click on an element with the error class, call the custom highlight event and pass parameters to it $(".error").click(function())( // using the second argument we will pass the data to the event handler $(this).closest(". module").find("p").trigger("highlight",["red","(color red)"]); ));

The input event fires when the value of an , , or element has been changed.

Bubbles Cancelable Interface Event handler property
Yes
No
InputEvent
GlobalEventHandlers.oninput
HTML JavaScript const input = document.querySelector("input"); const log = document.getElementById("values"); input.addEventListener("input", updateValue); function updateValue(e) ( log.textContent = 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 Internetinput event
Chrome Full support YesEdge Full support 79 Full support 79 No support 12 - 79

Notes

Notes Not supported on select , checkbox , or radio inputs.
Firefox Full support YesIE Partial support 9

The previous topic looked at events that occur when keys are pressed. In this topic we will look at other form events. Including sending the form to the server.

Element in focus

When a form element has focus, the focus event is fired, and when the element goes out of focus, the blur event is fired. Let's create an input field and output text to the console when it receives focus and when it loses focus:

HTML code:

There is no point in using these events to change the style of an element. There is a pseudo-class called focus in CSS for this purpose.

Entering a value

The input event occurs when the user types text into an input field. It is triggered when each character is added or removed, as well as when text is copied into the input field. In some browsers, it works unusually: every time a character is entered, 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 there is no problem. But if they are, then they will fire every time a symbol is added.

Let's add another tag to the page and display its value when entering text:

HTML code:

JavaScript:

28
29
30
31
32

var newv = document.getElementById("new_value"); newv.onchange = function () ( console.log("Value changed to: "+newv.value); );
Submitting a form

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 ​​of the form elements, and if any values ​​are entered incorrectly, the form is canceled. This usually displays a message indicating what needs to be corrected.

Let's place the created tags in the form and add a button to submit the form:

HTML code:

In the previous examples, the form elements have already been found, so the handler does not search again.

If the form is filled out correctly, that is, all fields have at least two characters, then the browser will try to launch 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 to test the script. If less than two characters are entered in one of the fields, a message will appear and the sending will be cancelled. If there are a lot of checks, then you can display a different message for each check and cancel submitting the form.