JavaScript event description

JavaScript in the browser uses an event-driven programming model. Everything starts with events. This is an introduction to JavaScript events and how event handling works

Introduction

JavaScript in the browser uses an event-driven programming model.

Everything starts with events.

The event may be DOM loading, completion of an asynchronous request to obtain, the user clicking an element or scrolling the page, or the user typing on the keyboard.

There are many different types of events.

Event handler

you can use itEvent handler, This is the function that is called when the event occurs.

You can register multiple handlers for the same event, and they will all be called when the event occurs.

JavaScript provides three ways to register event handlers:

Inline event handler

Due to its constraints, this style of event handler is rarely used today, but it was the only way in the early days of JavaScript:

<a href="site.com" onclick="dosomething();">A link</a>

DOM event handler

This is very common when an object has at most one event handler, because it is not possible to add multiple handlers in this case:

window.onload = () => {
  //window loaded
}

Most commonly used in processingXHRClaim:

const xhr = new XMLHttpRequest()
xhr.onreadystatechange = () => {
  //.. do something
}

You can use the following method to check if the handler has been assigned to the attributeif ('onsomething' in window) {}.

useaddEventListener()

this isModern way. This method allows registering the required number of handlers, and it is the most popular handler:

window.addEventListener('load', () => {
  //window loaded
})

Please note that IE8 and lower versions do not support this feature, but use its ownattachEvent()API. If you need to support older browsers, please keep this in mind.

Listen to different elements

You can listenwindowTo intercept "global" events (such as keyboard usage), you can listen to specific elements to check the occurrence of events, such as mouse clicks.

This is whyaddEventListenerSometimes calledwindow, Sometimes on DOM elements.

Event object

An event handler gets aEventObject as the first parameter:

const link = document.getElementById('my-link')
link.addEventListener('click', event => {
  // link clicked
})

This object contains many useful properties and methods, such as:

  • target, Is the DOM element that triggered the event
  • type, Event type
  • stopPropagation(), Called stop propagating events in the DOM

(View the full list).

Other attributes are provided by specific types of events, such asEventIs the interface for different specific events:

Each page has a linked MDN page, so you can check all their attributes.

For example, when a KeyboardEvent occurs, you can check which key was pressed in a readable format (Escape,EnterSo on and so forth)keyproperty:

window.addEventListener('keydown', event => {
  // key pressed
  console.log(event.key)
})

When a mouse event occurs, we can check which mouse button was pressed:

const link = document.getElementById('my-link')
link.addEventListener('mousedown', event => {
  // mouse button pressed
  console.log(event.button) //0=left, 2=right
})

Event bubbling and event capture

Bubbling and capture are the two models used by events to propagate.

Assuming your DOM structure is

<div id="container">
  <button>Click me</button>
</div>

You want to track when the user clicks the button, and there are 2 event listeners, one of thembuttonwith one#container. Remember that clicking on a child element will always propagate to its parent element unless you stop propagation (see below).

These event listeners will be called in order, and this order is determined by the event bubbling/capturing model used.

BlisteringIndicates that the event propagates from the clicked item (child item) to all its parent trees, starting from the nearest tree.

In our example,buttonWill be at#containerProcessing procedures.

CaptureOn the contrary: the external event handler is triggered before the more specific handler,button.

By default, all events will bubble.

You can choose to adopt event capture by applying the third parameter to addEventListener and setting it totrue:

document.getElementById('container').addEventListener(
  'click',
  () => {
    //window loaded
  },
  true
)

noteRun all capture event handlers first.

Then there are all bubbling event handlers.

The order follows this principle: the DOM traverses all elements starting from the Window object, and then finds the item that was clicked. When doing so, it will call any event handlers associated with the event (capture phase).

Once it reaches the target, it will repeat the process of traversing the parent tree until the Window object, and then call the event handler again (bubbling phase).

Stop spreading

Unless it stops, the event on the DOM element will propagate to all its parent element trees.

<html>
  <body>
    <section>
      <a id="my-link" ...>

Click eventaWill spread tosectionthenbody.

You can callstopPropagation()Event methods, usually at the end of the event handler:

const link = document.getElementById('my-link')
link.addEventListener('mousedown', event => {
  // process the event
  // ...

  event.stopPropagation()
})

The following is a list of the most common events you might handle.

load

loadkicked outwindowwithbodyThe element after the page is loaded.

Mouse event

clickTriggered when the mouse button is clicked.dblclickWhen the mouse is clicked twice. Of course in this caseclickWas fired before this incident.mousedown,mousemovewithmouseupCan be used in combination to track drag and drop events. Be carefulmousemove, Because it will trigger multiple times during mouse movement (seeThrottlingafter that)

Keyboard events

keydownTriggered when a keyboard button is pressed (and any time the key is repeated while the button is pressed)StayPress).keyupFires when the key is released.

scroll

ThisscrollEvent is triggeredwindowEvery time you scroll the page. Inside the event handler, you can check the current scroll position by checking the followingwindow.scrollY.

Remember, this event is not a one-time event. It will be triggered many times during the scrolling process, not just at the end or the beginning of the scrolling, so don’t do any heavy calculations or operations in the handler-useThrottlinginstead.

Throttling

As mentioned above,mousemovewithscrollThere are two events that are not triggered at once in each event, but their event handlers are continuously called for all the duration of the action.

This is because they provide coordinates so you can keep track of what is happening.

If you perform complex operations in the event handler, it will affect performance and bring a slow experience to site users.

Library that provides throttling functionRodasImplement it with more than 100 lines of code to handle all possible use cases. This is a simple and easy to understand implementation, it usessetTimeoutCache scroll events every 100 milliseconds:

let cached = null
window.addEventListener('scroll', event => {
  if (!cached) {
    setTimeout(() => {
      //you can access the original event at `cached`
      cached = null
    }, 100)
  }
  cached = event
})

Download mine for freeJavaScript beginner's manual


More js tutorials: