JavaScript - Types of events. JavaScript: Events Events for working with javascript input

JavaScript's ability to create dynamic html pages is based on three pillars. Two of them have already been discussed in previous articles. And the third is events.

  • Managing browser windows using the window object.
  • Managing objects inside a window is the DOM.
  • Execute JavaScript code on events.

An event is a computer's reaction to a user action. For example, with t.z. A javaScript event is considered to be the pressing of a keyboard button, the movement and clicking of mouse buttons, and the closing of the browser window. All events with t.z. javaScript are generated by document and browser objects (there is no concept of a 'user'). For example, when you click on a paragraph, the mouse click event is generated by an object - paragraph.

In order to be able to run some JavaScript code that reacts to events, you need to associate this code with an event generated from a specific object, i.e. with a specific event from a specific object. This action is called subscribing to an event.

Subscription means that we bind a function to a specific event from a specific object in the browser object model. And when this object creates (generates) this event, this function will automatically work.

  • onclick - clicking a mouse button.
  • ondblclick - double click of the mouse button.
  • onmousedown - the mouse button is pressed (moved down).
  • onmousemove - the mouse moves over the object (many events occur, mouse movement 1px = 1 event).
  • onmouseout - the mouse leaves the object.
  • onmouseover - the mouse moves over the desired object.
  • onmouseup – the mouse button is released (raised up).
  • onkeydown – the keyboard button is pressed (moved down).
  • onkeypress – pressing a keyboard button.
  • onkeyup – the keyboard button is released (raised up).
  • onblur – loss of input focus (blinking cursor).
  • onfocus - the moment the input focus is received by this element.
  • onchange – generated by the control after losing focus if the text has changed (for example, in a text field). The exception is the 'select' list element, in which this event is generated immediately, and not after losing focus.
  • onload - generated when the page has finished loading in the window. Typically used when you need to run some JavaScript code after the page has fully loaded.
  • onunload – occurs before the document is unloaded from the window (that is, when we close this document or move to another document).
  • onreset – the form has been reset.
  • onsubmit – the data form has been submitted.
Subscribe to events
  • Subscription via JavaScript. This method is used in most cases. First, we need to find the object of the element from which we want to subscribe, for example, through the getElementById method (indicate the id to the desired element).
function myFunc () ( //created a simple function alert ("hello"); ) function pageInit () ( var p= document. getElementById ("1"); p. onclick= myFunc; ) //called the function to fire the window event . onload=pageInit; //event will fire when the page loads< p id= 1 >Paragraph 1 //set id for paragraph
  • Subscribe via html code. The disadvantage of this method is that the html code is clogged with javaScript code; In addition, there are several limitations, and in complex cases it is inconvenient to use.
< script type= "text/javascript" >function myFunc () ( //created a simple function alert ("hello" ); )< p onclick= "myFunc()" >Paragraph 2 //called the function Event Processing Model

When an event occurs on an element, similar events should occur on all its parent elements up to the very top of the page (up to the ‘body’, since it is the main area of ​​the document). Therefore, any event that occurs on the page occurs in the body.

The question then becomes, in what order will such events occur? In modern browsers, the event handling model is called the 'bubble model'. Its essence: first, an event occurs at the element that was clicked, then at its parent, and so on up to the very top - up to ‘body’.

Element --> element 2 --> document --> window

Event parameters (event object)

There is an event object that has many properties. By reading these properties, you can get information about events. To obtain information, you must first obtain the object itself.

Main properties of this object:

  • x, y - mouse coordinates at the moment the event occurs.
  • clientX, clientY - the same.
  • offsetX, offsetY - the same thing, but this is the mouse offset relative to parent element.
  • screenX, screenY - screen coordinates.
  • button - which mouse button was pressed (0 - not pressed, 1 - left button pressed, 2 - right button pressed, 4 - middle button pressed).
  • keyCode - numeric code of the pressed keyboard key.
  • srcElement - the element that generated the event.
  • fromElement - the element from which the mouse moved.
  • toElement - an indication of the object that the mouse ran over.
  • cancelBubble is a non-standard way if you give it true, then the ‘pop-up bubble’ will be cancelled; or you can replace the code of the key that the user pressed.

In this lesson, we'll look at the main types of events that you can intercept using JavaScript to execute some code.

Event categories

All JavaScript events can be divided into the following categories: Mouse Events, Keyboard Events, Frame/Object Events, Form Events, Drag Events , Animation Events, Clipboard Events, Media Events, Transition Events, Server-Sent Events, Touch Events, Print Events (Print Events), miscellaneous events (Misc Events).

Attention: all events in JavaScript are written in lowercase (small) letters.

Mouse events
  • mousedown - event occurs when the mouse button is pressed over some element, but has not yet been released.
  • mouseup - the event occurs when the mouse button over some element has passed from the pressed state to the released state.
  • click - the event occurs when the user clicks on an element. The order in which click events occur (for the left and middle mouse buttons) is mousedown -> mouseup -> click .
  • contextmenu - the event occurs when the user right-clicks on an element. The order of events associated with the contextmenu (for the right mouse button) is mousedown -> mouseup -> contextmenu .
  • dblclick - event occurs when the user double-clicks an element. The order of occurrence of events associated with dblclick is: mousedown -> mouseup -> click -> mousedown -> mouseup -> click -> dblclick .
  • mouseover - the event occurs when the mouse cursor enters an area owned by an element or one of its children.
  • mouseout - event occurs when the mouse cursor moves out of an area owned by an element or one of its children.
  • mousemove - event occurs when the mouse cursor moves inside the area belonging to the element.
  • mouseenter - event occurs when the mouse pointer enters an area owned by an element. This event is often used in conjunction with the mouseleave event, which occurs when the mouse pointer leaves the area owned by an element. The mouseenter event is similar to the mouseover event and differs only in that the mouseenter event does not bubble (we will get to know the concept of event bubbling a little later).
  • mouseleave - event occurs when the mouse pointer leaves the area owned by the element. The mouseleave event is similar to the mouseout event and differs only in that the mouseleave event does not bubble (we will get to know the concept of event bubbles a little later).
Keyboard events

The order of occurrence of events is: keydown -> keypress -> keyup .

  • keydown - the event occurs when a key on the keyboard above an element is pressed but not yet released.
  • keyup - the event occurs when a pressed key on the keyboard above an element changes to the released state.
  • keypress - event occurs when the user presses a key on the keyboard above an element.
Object and Frame Events
  • beforeunload - the event occurs before the document is unloaded. This event allows you to display an additional message in the confirmation dialog, "Are you sure you want to leave this page?" The standard message that appears when closing a document may differ depending on the different browsers. But you cannot change or delete it, you can only use this method to add your own message to it, which will be displayed along with the default message.
  • error - the event is triggered when an error occurs, which occurs when loading an external file (for example, a document or image).
  • hashchange - the event occurs when the anchor part (starts with the "#" symbol) of the current URL changes.
  • load - event occurs when loading of an object is completed. The load event is most often used on the body element to execute a script immediately after the web page has fully loaded.
  • unload - the event occurs when a page is unloaded (for example, when a browser tab (window) is closed).
  • pageshow - event occurs when the user navigates to a web page, i.e. after the page becomes available to the user. The pageshow event is similar to the load event, except that it fires every time the page is loaded, even if it is loaded from the cache. When a page is first loaded, the pageshow event fires immediately after the load event.
  • pagehide - the event occurs when the user leaves the page (the pagehide event occurs before the unload event). In addition, this event, unlike the unload event, does not prevent page caching.
  • resize - event occurs when the browser window is resized.
  • scroll - The event occurs when you scroll the content of an element that has a scrollbar.
Form and Control Events
  • focus - the event occurs when the element receives focus. This event does not pop up.
  • blur - event occurs when an object loses focus. This event does not pop up.
  • focusin - event occurs when the element receives focus. The focusin event is similar to the focus event, but differs from it in that it bubbles. Therefore, it can be used when you need to find out who is losing focus: the element or its child?
  • focusout - event occurs when an element is about to lose focus. The focusout event is similar to the blur event, but differs from it in that it bubbles. Therefore, it can be used when you need to find out who is losing focus: the element or its child?
  • change - the event occurs when the element's value changes, but after the element has lost focus. In addition to the change event, JavaScript also has a similar input event, which differs from the change event in that it occurs immediately after the element's value changes. The change event, unlike the input event, also works with keygen and select elements. For radiobuttons and checkboxes, the change event occurs when the state of these elements changes.
  • input - the event occurs after the value of the input element or textarea element changes.
  • invalid - The event occurs when an input element whose data needs to be sent along with other form data to the server contains invalid data.
  • reset - the event occurs before the form is cleared, which is done by an input element with type="reset" .
  • search - The event occurs after the user presses the Enter key or clicks the " x " (cancel) button on an input element with type="search" .
  • select - the event occurs after you have selected some text in the element. The select event is mainly used for an input element with type="text" or textarea .
  • submit - the event occurs before the form is submitted to the server.
Drag Events

Events associated with the dragged object (draggable target, source object):

  • dragstart – the event occurs when the user starts dragging an element;
  • drag – event occurs when the user drags an element;
  • dragend – the event occurs when the user has finished dragging the element, i.e. when I released the mouse cursor.

Events associated with the drop target that receives the draggable target:

  • dragenter – the event occurs when a draggable target has entered the area of ​​a drop target that can accept a draggable target.
  • ragleave - the event occurs when a dragged object (draggable target) leaves the boundaries of the element (drop target) that can accept it.
  • dragover - the event occurs when a draggable target moves into the area of ​​an element (drop target) that can accept it.
  • drop - the event occurs when the user releases a draggable object into the area of ​​an element (drop target) that can accept it.
Animation Events

Three events that can happen while a CSS animation is running:

  • animationstart - Occurs when the CSS animation has started.
  • animationiteration - Occurs when a CSS animation is executed repeatedly.
  • animationend - occurs when CSS animation ended.
Clipboard events
  • copy - event occurs when the user copies the contents of an element. The copy event also occurs when the user copies an element (for example, images created with the img element). The copy event is used primarily for input elements with type="text" .
  • cut - event occurs when the user cuts the content of an element.
  • paste - the event occurs when the user pastes some content into an element.
Print Events
  • afterprint - The event occurs when the page begins to print (that is, after clicking the Print button in the dialog box) or if the Print dialog box has been closed.
  • beforeprint - the event occurs before the page is printed, i.e. before opening the Print dialog box.
Transition Events
  • transitionend - the event fires when the CSS transition is complete. Note: If a transition is removed before completion (for example, if CSS property transition-property has been removed), then the transitionend event will not fire.
Events sent by the server
  • error - the event occurs when an error occurs with the event source. The error usually occurs when communication is broken. If this happens, the EventSource object will automatically try to connect to the server.
  • open - the event occurs when the connection to the event source is open.
  • message - the event occurs when a message is received through the event source.
    The message event object supports the following properties:
    • data - contains the message.
    • origin - URL of the document that triggered the event.
    • lastEventId - identifier (id) of the last received message.
Media Events

During the audio/video loading process, events occur in the following order: loadstart -> durationchange -> loadedmetadata -> loadeddata -> progress -> canplay -> canplaythrough .

  • abort - event occurs when audio/video loading is interrupted. This event occurs when the download of media data was interrupted (cancelled), and not because an error occurred.
  • error - event occurs when an error occurs while loading audio/video.
  • stalled - the event occurs when the browser tries to receive media data, but the data is not available.
  • - the event occurs when the browser starts searching for the specified audio/video, i.e. when the download process begins.
  • durationchange - event occurs when the duration of the audio/video changes. If audio/video is loaded, the duration will vary from "NaN" to the actual duration of the audio/video.
  • loadedmetadata - event fired when metadata for the specified audio/video has been loaded. Audio/video metadata consists of: duration, size (video only) and text track.
  • loadeddata - the event occurs after the first frame of media has loaded.
  • progress - event occurs when the browser downloads the specified audio/video.
  • canplay - the event occurs when the browser can start playing the specified audio/video (that is, when the audio/video stream is buffered enough for the browser to start playing it).
  • canplaythrough - the event occurs at the point in time when the browser can play the specified media without stopping for buffering.
  • ended - the event occurs when audio/video playback has completed (reached the end). This event can be used to display messages like “Thank you for your attention”, “Thank you for watching”, etc.
  • pause - event occurs when audio/video playback is paused by the user or by code (programmatically).
  • play - event occurs when audio/video playback starts. It also occurs when the audio/video has been unpaused and begins to play.
  • playing - The event occurs when audio/video is playing after it has been paused or stopped for buffering.
  • ratechange - event occurs when the audio/video playback speed changes.
  • seeking - the event occurs when the user begins to move the slider (transition) to a new time position of the audio/video being played.
  • sought - the event occurs when the user has finished moving the slider (transition) to a new temporary position of the audio/video being played. The sought event is the opposite of the seeking event. To get the current playback position, use the currentTime property of the Audio / Video object.
  • timeupdate - the event occurs when the time position of the audio/video being played changes.
    This event occurs:
    • when playing an audio/video stream.
    • when moving the slider to a new time position of the audio/video being played.
    The timeupdate event is often used in conjunction with the Audio/Video object's currentTime property, which returns the current time position of the currently playing audio/video in seconds.
  • volumechange – the event occurs every time the volume of the playing video/audio stream changes.
    This event occurs when:
    • increasing or decreasing the volume;
    • muting or unmuting the sound.
  • waiting - the event occurs when the video is stopped for buffering.
Various events
  • toggle - The event occurs when the user opens or closes the details element. The details element is designed to create additional information that the user can view or hide as needed.
  • wheel - the event occurs when the mouse wheel scrolls forward or backward over an element.
Tasks
  • Is the "Keypress on keyboard (onkeypress)" event complex? And if it is, then as a result of what simple events does it arise?
  • For example, you have 2 p elements and the user moves the mouse from an area belonging to one p element to an area belonging to another p element. What events occur in this case, and what elements generate them?
  • The topic of the events is very important and very interesting. Thanks to it, you can do a lot of interesting things that the user will be delighted with. An event in JavaScript is a specific action that is triggered either by the user or the browser. For example, an event could be a mouse click on a button, mouse movement, focusing on an element, changing a value in a text field, resizing a browser window, and so on.

    I have prepared a table with all the events (that I know from at least) in JavaScript. In it you will find, firstly, the name of the event, elements that can generate this event and a description of the JavaScript event itself.

    EventAn objectCause of occurrence
    AbortionImageInterrupting image loading
    BlurLost element focus
    ChangeFileUpload, Select, Text, TextareaChange value
    ClickArea, Button, Checkbox, Document, Link, Radio, Reset, SubmitMouse click on an element
    DblClickArea, Document, LinkDouble click on an element
    DragDropWindowMove to browser window
    FocusButton, Checkbox, FileUpload, Frame, Layer, Password, Radio, Reset, Select, Submit, Text, Textarea, WindowSetting focus on an element
    KeyDownPressing a key on the keyboard
    KeyPressDocument, Image, Link, TextareaHolding a key on the keyboard
    KeyUpDocument, Image, Link, TextareaReleasing a key on the keyboard
    LoadDocument, Image, Layer, Window
    MouseDownButton, Document, LinkMouse button pressed
    MouseMoveWindowMouse in motion
    MouseOutArea, Layer, LinkThe mouse goes beyond the borders of the element
    MouseOverArea, Layer, LinkThe mouse is over the element
    MouseUpButton, Document, LinkMouse button released
    MoveFrameMoving an element
    ResetFormReset form
    ResizeFrame, WindowResizing
    SelectText, TextareaText selection
    SubmitFormData transfer
    UnloadWindowUnloading the current page

    Now let's figure out how to use events in JavaScript. There are so-called event handlers. Event handlers determine what will happen when a certain event occurs. Event handlers in JavaScript have the following general form:

    OnEventName

    That is, first comes the prefix “on”, and then the name of the event, for example, the following event handlers: onFocus, onClick, onSubmit, and so on. I think there are no questions here. And now the main question: “How to use events in JavaScript?”. The scope of their application is huge, and now we will look at one problem. There are three links on the page. Each of the links is responsible for a different background color (for example, white, yellow and green). At first the background is white. When you hover your mouse over a specific link, the background color changes. When you move the mouse away, the background color returns to the default color. When you click on a link, the background color is retained as the default.




    a (
    color:blue;
    text-decoration: underline;
    cursor: pointer;
    }


    var default_color = "white";

    function setTempColor(color) (
    document.bgColor = color;
    }

    function setDefaultColor(color) (
    default_color = color;
    }

    function defaultColor() (
    document.bgColor = default_color;
    }



    White
    Yellow
    Green

    Let's look at this script, or rather an entire HTML page with JavaScript and CSS support (in other words, this is an example of DHTML). First come the usual HTML tags, with which any HTML page begins. Next, we create a style in which we require that all links on a given page be blue, underlined, and that the mouse pointer on them be in the form of a "Pointer". You may say: “Why do you need to set a style? After all, the links will be exactly the same.” That’s right, links, but we don’t have links as such (after all, there is no href attribute in the tag), so they will be simple black text by default (however, you can also click on the text). Therefore, style is a must. You can remove it and see what happens. Better yet, add the href attribute (with any value, even empty) and explain why the script stopped working. Then JavaScript begins. We create a variable default_color responsible for the default color. Next come three functions:

    The setTempColor() function is responsible for temporarily changing the color.

    The setDefaultColor() function is responsible for changing the default color.

    The defaultColor() function sets the default background color.

    Then there are links with attributes in the form of event handlers. When you hover the mouse over a link, the MouseOver event occurs; accordingly, the onMouseOver event handler calls the setTempColor() function and passes the corresponding parameter. When you remove the mouse from an element, the MouseOut event is raised, and then the defaultColor() function is called, which sets the background color to the default color. And finally, when the mouse clicks on the link (onClick handler), the setDefaultColor() function is called, which sets the color specified in the parameter to the default background color. As you can see, everything is quite simple.

    This was the principle of using events in JavaScript, and then everything depends only on your imagination!

    Some programs using JavaScript event work directly with user input. The moment of occurrence and the order of such interactions cannot be predicted in advance.

    Event Handlers

    You can react to a key press by constantly reading its state to catch the moment the key is pressed before it is released again.

    This is how data input was processed on primitive machines. More advanced is detecting a keystroke and queuing it. The program can then periodically check the queue of new events and react to what it finds there. In this case, the program must remember to scan the queue and do so often.

    In the period from pressing a key until the program detects this event, it actually does not respond to requests. This approach is called polling (survey).

    Most programmers try to avoid it if possible.

    The best way is to implement a system that gives the code the ability to react to events as they happen. Browsers implement this by providing the ability to register handler functions for specific JavaScript events:

    Click on this document to activate the handler.

    addEventListener("click", function() ( console.log("You clicked!"); ));

    The addEventListener function is registered so that its second argument is called whenever the event described by the first argument occurs.

    Events and DOM nodes

    Each browser event handler is registered with a context. When the addEventListener function is called, it is called as a method for the entire window, since in the browser the global range is equivalent to window object. Each DOM element has its own addEventListener method, which allows you to listen for events specifically on that element:

    Click on me

    There is no handler here.

    var button = document.querySelector("button"); button.addEventListener("click", function() ( console.log("Button clicked."); ));

    IN in this example the handler is connected to the button node. JavaScript mouse events fire the handler, but clicks in the rest of the document do not.

    By setting the node's onclick attribute, we get the same result. But a node only has one onclick attribute, so you can only register one handler per node. The addEventListener method allows you to add any number of handlers. This way we are insured against accidental replacement of a processor that has already been registered.

    The removeEventListener method is called with arguments similar to addEventListener . It removes the handler:

    One-time button var button = document.querySelector("button"); function once() ( console.log("Done."); button.removeEventListener("click", once); ) button.addEventListener("click", once);

    To cancel a handler function, we give it a name (for example, once ). So we pass it to both addEventListener and removeEventListener.

    Event Objects

    Although we didn't mention it in the examples above, the JavaScript event handlers function is passed an argument: the event object. It provides additional information about the event. For example, if we want to know which mouse key was pressed, we need to get the value of the which event object property:

    Click on me with any mouse key var button = document.querySelector("button"); button.addEventListener("mousedown", function(event) ( if (event.which == 1) console.log("Left button"); else if (event.which == 2) console.log("Middle button" ); else if (event.which == 3) console.log("Right button"); ));

    The information stored in an object varies depending on the type of event. The object's type property always contains a string identifying the event (for example, "click" or "mousedown").

    Spreading

    Event handlers (such as JavaScript touch events) registered for parent nodes will also receive events that occur on child elements. If a button inside a paragraph was clicked, the paragraph's event handlers will also receive click event.

    An event propagates from the node in which it occurred, to the parent node, and to the document root. After all handlers registered in a particular node have taken action in turn, handlers registered for the entire window are able to respond to the event.

    At any time, the event handler can call the stopPropagation method on the event object to prevent the event from propagating further. This can be useful when you have a button inside another interactive element and you don't want clicking the button to trigger the behavior specified for clicking on external elements.

    In the following example, we register "MouseDown" handlers for both the button and the paragraph. When you right-click (JavaScript mouse events), the handler calls the stopPropagation method, which prevents the paragraph handler from running. When you click on the button with another mouse key, both handlers are launched:

    A paragraph and a button in it.

    var para = document.querySelector("p"); var button = document.querySelector("button"); para.addEventListener("mousedown", function() ( console.log("Handler for paragraph."); )); button.addEventListener("mousedown", function(event) ( console.log("Handler for button."); if (event.which == 3) event.stopPropagation(); ));

    Most event objects have a target property that points to the node where they occurred. You can use this property to avoid accidentally handling some event that propagates up from the node.

    You can also use a JavaScript event target to extend the scope of an event of a certain type. For example, if you have a node containing a long list of buttons, it is more convenient to register one click handler for the outer node and use the target property to track whether the button was clicked, rather than registering handler instances for all buttons:

    A B C document.body.addEventListener("click", function(event) ( if (event.target.nodeName == "BUTTON") console.log("Clicked", event.target.textContent); ));

    Default Actions

    Many events have default actions associated with them. If you click on a link, it will take you to the target element of the link. If you click the down arrow, the browser will scroll down the page. If you right-click, a context menu will open.

    For most event types, JavaScript event handlers are called before default actions are performed. If you do not want the default behavior to occur, you must call the preventDefault method on the event object.

    Use it to implement custom keyboard shortcuts or context menus. Or, to override the behavior that users expect. Below is a link that cannot be followed:

    MDN var link = document.querySelector("a"); link.addEventListener("click", function(event) ( console.log("Nope."); event.preventDefault(); ));

    Try not to do this unless you have a good reason to do so.

    Depending on the browser, some events may not be intercepted. IN Google Chrome for example, the keyboard shortcut (JavaScript event keycode) to close the current tab (Ctrl-W or Command-W) cannot be processed using JavaScript.

    Key Events

    When the user presses a key on the keyboard, the browser fires the "keydown" event. When he releases the key, the "keyup" event fires:

    This page turns purple when you press the V key.

    addEventListener("keydown", function(event) ( if (event.keyCode == 86) document.body.style.background = "violet"; )); addEventListener("keyup", function(event) ( if (event.keyCode == 86) document.body.style.background = ""; ));

    This event also fires when the user presses and holds a key, or while the key is held down. For example, if you want to increase the speed of a character in a game by pressing an arrow key, and decrease it again by releasing the key, then you need to be careful not to increase the speed each time the key is pressed.

    The previous example used the event object's keycode JavaScript property. With its help, it is determined which key was pressed or released. It's not always obvious how to translate a key's numeric code to an actual key.

    The Unicode character code is used to read the letter and number key values. It is associated with the letter (uppercase) or number indicated on the key. The charCodeAt method for strings allows you to get this value:

    console.log("Violet".charCodeAt(0)); // → 86 console.log("1".charCodeAt(0)); // → 49

    Other keys have less predictable key codes associated with them. The best way Determining the code you need is a matter of experimenting. Register a keypress event handler that captures the keycodes it receives and presses the desired key.

    Keys such as Shift , Ctrl , Alt generate events like regular keys. But when tracking key combinations, you can also determine whether those keys are pressed by the properties of the keyboard events and JavaScript mouse events: shiftKey , ctrlKey , altKey and metaKey :

    To continue, press Ctrl-Space.

    addEventListener("keydown", function(event) ( if (event.keyCode == 32 && event.ctrlKey) console.log("Continuing!"); ));

    The "keydown" and "keyup" events provide information about actual keypresses. But what if we need the input text itself? Retrieving text from keycodes is inconvenient. There is an event for this, "keypress", which fires immediately after "keydown". It repeats along with "keydown" as long as the key is pressed. But only for the keys with which characters are entered.

    The charCode property on the event object contains a code that can be interpreted as the Unicode character code. We can use the String.fromCharCode function to convert this code into a single character string.

    Set the input focus to this page and type something.

    addEventListener("keypress", function(event) ( console.log(String.fromCharCode(event.charCode)); ));

    The DOM node at which the event occurs depends on the element that had input focus when the key was pressed. Regular nodes cannot have input focus (unless you set the tabindex attribute to them), but elements such as links, buttons, and form fields can.

    If no specific element has input focus, then the target node for key events and JavaScript touch events is document.body .

    Mouse clicks

    Pressing a mouse button also triggers a series of events. The "mousedown" and "mouseup" events are similar to the "keydown" and "keyup" events. They are triggered when a mouse button is pressed and released. These events occur on the DOM nodes that were hovered over when the event occurred.

    For a shared node that has both a mouse press and release, the click event is fired after the mouseup event. For example, if you press the mouse button on one item, and then move the cursor to another item and release the button, the click event will occur on the element that contains both of these items.

    If two clicks occur close to each other, the "dblclick" (double click) event is also fired. It appears after the second click. To get exact information about the location where the mouse event occurred, you need to get the value of the pageX and pageY properties, which contain the coordinates of the event (in pixels) relative to the upper left corner of the document.

    Below is an implementation of a primitive drawing program. Each time you click the mouse in the document (under the cursor), a dot is added:

    body ( height: 200px; background: beige; ) .dot ( height: 8px; width: 8px; border-radius: 4px; /* rounded corners */ background: blue; position: absolute; ) addEventListener("click", function (event) ( var dot = document.createElement("div"); dot.className = "dot"; dot.style.left = (event.pageX - 4) + "px"; dot.style.top = (event .pageY - 4) + "px"; document.body.appendChild(dot); ));

    The clientX and clientY properties are similar to pageX and pageY , but they relate to the visible part of the document. They can be used to compare mouse coordinates with the coordinates returned by the getBoundingClientRect function.

    Mouse movement

    Every time the mouse moves, the “mousemove” event from the JavaScript mouse events set is fired. It can be used to track the position of the mouse. This is used when implementing the ability to drag elements with the mouse.

    In the following example, the program displays a panel and sets event handlers so that when dragged, the panel becomes narrower or wider:

    Drag the edge of the panel to change its width:

    var lastX; // Tracks the last X position of the mouse var rect = document.querySelector("div"); rect.addEventListener("mousedown", function(event) ( if (event.which == 1) ( lastX = event.pageX; addEventListener("mousemove", moved); event.preventDefault(); // Prevents selection ) ) ); function buttonPressed(event) ( if (event.buttons == null) return event.which != 0; else return event.buttons != 0; ) function moved(event) ( if (!buttonPressed(event)) ( removeEventListener( "mousemove", moved); ) else ( var dist = event.pageX - lastX; var newWidth = Math.max(10, rect.offsetWidth + dist); rect.style.width = newWidth + "px"; lastX = event .pageX; ) )

    Note that the "mousemove" handler is registered for the entire window. Even if the mouse moves out of the panel while resizing, we still update the panel's width and terminate JavaScript touch events when the mouse key is released.

    We must stop resizing the panel when the user releases the mouse button. Unfortunately, not all browsers set the which property for mousemove events. There is a standard buttons property that provides similar information, but it is also not supported in all browsers. Luckily, all major browsers support one thing: either buttons or which . The buttonPressed function in the example above first tries to use the buttons property, and if it's not available, goes to which .

    When the mouse cursor moves over or leaves a node, the "mouseover" or "mouseout" events are fired. They can be used to create hover effects, display some kind of caption, or change the style of an element.

    To create such an effect, it is not enough to simply start displaying it when the mouseover event occurs and end after the mouseout event. When the mouse moves from a node to one of its children, a "mouseout" event occurs for the parent node. Although the mouse pointer has not left the node's spread range.

    To make matters worse, these JavaScript events are propagated just like other events. When the mouse leaves one of the child nodes for which a handler is registered, the "mouseout" event will be raised.

    To work around this issue, you can use the relatedTarget event object property. When the "mouseover" event occurs, it indicates which element was hovered over before. And in the event of a “mouseout” - to which element the pointer is moved. We will only change the mouseover effect when the relatedTarget is outside our target node.

    In this case, we are changing the behavior because the mouse was hovering over the node from outside of it (or vice versa):

    Hover your mouse over this paragraph.

    var para = document.querySelector("p"); function isInside(node, target) ( for (; node != null; node = node.parentNode) if (node ​​== target) return true; ) para.addEventListener("mouseover", function(event) ( if (!isInside (event.relatedTarget, para)) para.style.color = "red"; )); para.addEventListener("mouseout", function(event) ( if (!isInside(event.relatedTarget, para)) para.style.color = ""; ));

    The isInside function tracks the parent links of a given node or until it is reached top part document (when node is null ). Or the parent element we need will not be found.

    A hover effect is much easier to create using the CSS:hover pseudo-selector, as shown in the following example. But when the hover effect involves something more complex than just changing the style of the target node, then you need to use a trick using the mouseover and mouseout events (JavaScript mouse events):

    Scroll Events

    Every time an element is scrolled, a JavaScript scroll event is fired on it. It can be used to track what's in this moment viewed by the user; to disable animation located outside the viewport.

    In the following example, we display a progress bar in the top right corner of the document and update it so that it fills with a different color piece by piece as we scroll down the page:

    .progress ( border: 1px solid blue; width: 100px; position: fixed; top: 10px; right: 10px; ) .progress > div ( height: 12px; background: blue; width: 0%; ) body ( height: 2000px ; )

    Scroll me...

    var bar = document.querySelector(".progress div"); addEventListener("scroll", function() ( var max = document.body.scrollHeight - innerHeight; var percent = (pageYOffset / max) * 100; bar.style.width = percent + "%"; ));

    By setting the element's position or fixed property, we get the same result as setting position:absolute . But this also locks the element from scrolling along with the rest of the document. As a result, the progress indicator will be statically fixed in the top corner. Inside it is another element, the size of which changes in accordance with the current progress.

    We use % rather than px as the unit of measurement when setting the width, so that the element's dimensions change proportionally to the size of the progress bar.

    The global variable innerHeight contains the height of the window, which we must subtract from the total available scrollable height of the document. You cannot scroll down the window when you reach the bottom of the document. With innerHeight innerWidth can also be used. Dividing pageYOffset (the current scroll box position) by the maximum allowed scroll position and multiplying by 100 gives us the percentage for the progress bar.

    Calling preventDefault on a JavaScript scroll event does not prevent scrolling. The event handler is called only after scrolling occurs.

    Input focus events

    When an element has input focus, the browser fires a "focus" event on it. When input focus is removed, the "blur" event is fired.

    These two events do not spread. The parent element handler is not notified when the child element has input focus.

    The following example displays a tooltip for text field, which currently has input focus:

    Name:

    Age:

    var help = document.querySelector("#help"); var fields = document.querySelectorAll("input"); for (var i = 0; i< fields.length; i++) { fields[i].addEventListener("focus", function(event) { var text = event.target.getAttribute("data-help"); help.textContent = text; }); fields[i].addEventListener("blur", function(event) { help.textContent = ""; }); }

    The window object receives the "focus" and "blur" events when the user navigates to or leaves the tab, browser window in which the document is displayed.

    Load event

    When the page finishes loading, a JavaScript event “load” is raised for the document body and window objects. It is used to schedule the initialization of actions that require loading the entire document. Don't forget that the content is launched immediately when this tag is encountered. Sometimes it's too early. For example, when a script needs to do something with parts of a document that load after the .

    and script tags that load external files also contain a "load" event. It indicates that the file that was associated with them has been downloaded. Like input focus events, load events are not propagated.

    When we close a page or move to another (for example, by clicking on a link), the “beforeunload” event is fired. It is used to prevent the user from accidentally losing what he was working on after closing the document.

    Preventing a page from unloading is not done using the preventDefault method. Instead, a string is returned from the handler. It is used in a dialog box that asks the user whether they want to stay on the page or leave it. This mechanism ensures that the user will have the opportunity to leave the page, even if a malicious script is running, the purpose of which is to keep the visitor on the page.

    Script execution sequence

    Various factors can trigger script execution: reading a tag, occurrence of an event. The requestAnimationFrame method specifies a function call before the next page is re-rendered. This is another way that scripts can be run.

    JavaScript select events and all the others can fire at any time, but two scripts will never fire at the same time in the same document. If a script is already running, event handlers and code snippets scheduled by another script will have to wait their turn. This is the reason why the document freezes when the script is running for a long time. The browser does not respond to clicks and other events because it cannot fire event handlers until the current script finishes running.

    Some programming environments allow you to create multiple threads of execution that run simultaneously. By providing the ability to perform multiple tasks simultaneously, you can increase the speed of program execution. But when we have multiple actions that affect the same parts of the system at the same time, it becomes more difficult for the program to perform them.

    If you need to run processes in background Without freezing the page, browsers provide us with what are called web workers. It is a JavaScript sandbox that runs on the document alongside the main program and can only communicate with it by sending and receiving messages.

    Let's say that in a file called code/squareworker.js we have the following code:

    addEventListener("message", function(event) ( postMessage(event.data * event.data); ));

    Imagine that the number you are squaring is very large, lengthy to calculate, and you need to perform the calculation on a background thread. This code starts web workers, sends it some messages and prints out the responses:

    var squareWorker = new Worker("code/squareworker.js"); squareWorker.addEventListener("message", function(event) ( console.log("The worker responded:", event.data); )); squareWorker.postMessage(10); squareWorker.postMessage(24);

    The postMessage function sends a message that triggers the message event at the receiver. The script that created the web workers sends and receives messages through the Worker object. Using this object, the environment interacts with the script that created it, sending information and listening to it in its global with the original script.

    Setting timers

    The setTimeout function is similar to requestAnimationFrame. It calls another function that will be called later. But instead of calling the function the next time the page is rendered, it waits a certain number of milliseconds. In that JavaScript example event the page background turns from blue to yellow after two seconds:

    document.body.style.background = "blue"; setTimeout(function() ( document.body.style.background = "yellow"; ), 2000);

    Sometimes we need to cancel a function we have planned. This is done by storing the return value of setTimeout and calling clearTimeout on it:

    var bombTimer = setTimeout(function() ( console.log("BOOM!"); ), 500); if (Math.random()< 0.5) { // 50% chance console.log("Defused."); clearTimeout(bombTimer); }

    The cancelAnimationFrame function works the same as clearTimeout . It is called by the value returned by requestAnimationFrame to cancel the frame (if it has not already been called).

    A similar set of functions, setInterval and clearInterval are used to set a timer that should repeat an action every X milliseconds:

    var ticks = 0; var clock = setInterval(function() ( console.log("tick", ticks++); if (ticks == 10) ( clearInterval(clock); console.log("stop."); ) ), 200);

    Splitting up

    Some event types can be fired many times within a short period of time (such as "mousemove" and javascript scroll event). When handling such events, you need to be careful that it doesn't take too long, otherwise the handler will take so long to perform the action that interaction with the document becomes slow and choppy.

    If you need to do something non-standard in such a handler, you can use setTimeout to make sure it doesn't take too long. This is commonly referred to as event splitting. There are several different approaches to crushing.

    In the first example we want to do something while the user is typing. But we don't want to do this after every keypress event. When the user is typing quickly, you need to wait until there is a pause. Instead of immediately executing the action in the event handler, we set a delay. We also clear the previous delay (if any). If events occur at short intervals (less than the delay we set), then the delay from the previous event is canceled:

    Type something here... var textarea = document.querySelector("textarea"); var timeout; textarea.addEventListener("keydown", function() ( clearTimeout(timeout); timeout = setTimeout(function() ( console.log("You stopped typing."); ), 500); ));

    Passing an undefined value for clearTimeout or calling it on a delay that is already running will have no effect. We no longer have to be careful about when to call it, we just do it for every event.

    You can use a different script if you need to separate the answers over a short period of time. But at the same time, they should be launched during a series of events, and not just after it. For example, you can send the current mouse coordinates in response to mousemove events (JavaScript mouse events), but only every 250 milliseconds:

    function displayCoords(event) ( document.body.textContent = "mouse is at " + event.pageX + ", " + event.pageY; ) var scheduled = false, lastEvent; addEventListener("mousemove", function(event) ( lastEvent = event; if (!scheduled) ( scheduled = true; setTimeout(function() ( scheduled = false; displayCoords(lastEvent); ), 250); ) ));

    Conclusion

    Event handlers allow us to detect and respond to events over which we have no direct control. To register such a handler, use the addEventListener method.

    Each event has a specific type (“keydown”, “focus”, etc.) that identifies it. Most events are raised on a specific DOM element and then propagated to the element's parent nodes. This allows handlers associated with these elements to process them.

    When a handler is called, it is passed an event object with additional information about action. This object also contains methods to stop further propagation of the event (stopPropagation) or to prevent the default browser from processing the event (preventDefault).

    Keypresses generate the "keydown", "keypress" and "keyup" events. Clicking the mouse generates the "mousedown", "mouseup" and "click" events. Moving the mouse - "mousemove", "mouseenter" and "mouseout".

    A JavaScript scroll event can be defined using the "scroll" event, and changing focus can be defined using "focus" and "blur". Once the document has finished loading, the “load” event is raised for the window.

    Only one part of a JavaScript program can run at a time. Event handlers and other scheduled scripts must wait for other scripts in the queue to finish executing.

    This publication is a translation of the article “Handling Events”, prepared by the friendly project team

    JavaScript Events

    JavaScript, like other object-oriented languages, defines a number of events associated with document elements. Handlers make it possible to organize a reaction to the occurrence of events from a script. In this case, the corresponding handler is specified as an attribute of the HTML document element; the value of this attribute is a JavaScript expression. For example,

    - hovering and moving the mouse cursor over an element is accompanied by a change in the background color.


    - when the user tries to close the window and unload the document, a message is displayed


    - when you click on an image, a certain showPict() function is executed

    Half of the handlers are supported by almost all HTML elements (). Some events can be simulated using appropriate methods. Below is a list of events according to HTML specifications 4.0 and some events supported by MS IE. The interpretation of browsers may differ from the standard in terms of the applicability of the handler to certain elements

    Event handler Supporting HTML Elements Description

    Method
    imitation

    onAbort IMG Interrupting image loading
    onBlur The current element loses focus, i.e. move to another element. Occurs when the mouse is clicked outside an element or the tab key is pressed. blur()
    onChange INPUT, SELECT, TEXTAREA Changing the values ​​of form elements. Occurs after an element loses focus, i.e. after the blur event change()
    onClick Single click (mouse button pressed and released) click()
    onDblClick Almost all HTML elements Double click
    onError IMG, WINDOW Script execution error occurs
    onFocus A, AREA, BUTTON, INPUT, LABEL, SELECT, TEXTAREA Getting an element to focus (clicking on the element or pressing the Tab key again) focus()
    onKeyDown Almost all HTML elements A key is pressed on the keyboard
    onKeyPress Almost all HTML elements A key on the keyboard is pressed and released
    onKeyUp Almost all HTML elements Keyboard key released
    onLoad BODY, FRAMESET
    onMouseDown Almost all HTML elements Mouse button pressed within the current element
    onMouseMove Almost all HTML elements Move the mouse cursor within the current element
    onMouseOut Almost all HTML elements The mouse cursor is outside the current element
    onMouseOver Almost all HTML elements The mouse cursor is over the current element
    onMouseUp Almost all HTML elements Mouse button released within current element
    onMove WINDOW Moving a window
    onReset FORM Reset form data (click the button
    )
    reset()
    onResize WINDOW Resizing a Window
    onSelect INPUT, TEXTAREA Select text in the current element
    onSubmit FORM Submitting form data (clicking the button
    )
    submit()
    onUnload BODY, FRAMESET Attempting to close the browser window and unload the document