Introduction to events in JavaScript

Tram Ho

Events and actions or occurrences occur in the system you are programming, which the system tells you so you can respond to it in some way if you wish. For example, if a user clicks a button on a webpage, you might want to respond to an action to display something.

Each available event has an event handler , which is a block of code (usually the JavaScript function you created) that will run when the event is triggered. Note that sometimes it's called event listeners – they are interchangeable for our purposes, although strictly speaking, they work together.

Note: Web events are not part of the core JavaScript language – they are defined as part of the APIs built into the browser.

1. Ways of using web events

There are a few ways we can add event listener code to our website. In this section, we review a few ways and discuss which one we should use.

1.1. Event handler properties

There are many existing properties that contain event handler code we may encounter often:

The onclick attribute as an example is, in addition to it there are many other properties.

  • btn.onfocus and btn.onblur – The color changes when the button is focused and unfocused; try pressing tab to focus on the button and press tab again to focus away from the button. These are often used to display information about how to fill in form fields when they are focused, or display an error message if a form field has just been filled in with an incorrect value.
  • btn.ondblclick – The color changes only when the button is double-clicked.
  • window.onkeypress, window.onkeydown, window.onkeyup – The color changes when a key is pressed on the keyboard. The keypress event registering to a general press (button down and then up), while keydown and keyup refer to just the key down and key up parts of the keystroke, respectively. Note that it doesn't work if you try to register this event handler on the button itself – we've had to register it on the window object, which represents the entire browser window.
  • btn.onmouseover and btn.onmouseout – The color changes when the mouse pointer is moved so it begins hovering over the button, or when pointer stops hovering over the button and moves off of it, respectively.

There are some very common and available events for any element (for example, an onclik handler can register almost any element), but there are some special attributes that are only useful for certain situations. (for example, onplay only available with certain tags, like <video> )

1.2. Inline event handlers – don't use these

You can also see code samples like this in your code:

Or add JavaScript code directly into properties like for example:

You can find many equivalent HTML properties for many event handler properties, but you shouldn't use it – it's a bad practice . It is really difficult to manage the code and inefficient.

As a beginner, don't mix HTML files with your JS as it is difficult to parse, so all your JS files in another place will be better, you can apply each file. JS with many different HTML files.

Even putting them in a file, inline event handlers are not a good idea. A button is OK, but what happens if there are 100 buttons, you will have to add 100 attributes to the file, then maintaining code will become a nightmare. With JS, you can add an event handler function to all the buttons in the page no matter how many times by using the following:

Or another option uses the built-in method forEach built-in NodeList objects:

1.3. addEventListener() and removeEventListener()

The latest type of event handler is defined in the DOM level 2 object which provides the browser with a new function addEventListener() . This function is similar to event handler properties, but the syntax is a bit different

In the function addEventListener() function, there are two parameters, the name of the event we want to register and the code including the handler function we want to run in response to the event. Note that it is possible to put the entire code in the addEventListener() function as an anonymous function as follows:

This mechanism has several benefits over the previous two mechanisms. The first is that it has a removeEventListener() partner function that will remove the previously added listener. The following example will remove the listener added above:

This doesn't make much sense for small programs, but for larger, more complex programs it can be extremely effective to clean unused event handlers. In addition, for example, this allows you to have the same button perform different actions in different situations – all you have to do is add or delete event handlers.

Second, you can also register multiple handlers for the same listener. The following two handlers cannot be applied:

The second line overwrites the onclick value set by the first line. At that time you need

Then both functions are executed when the element is clicked.

There are also many other benefits through the event options, you can find out more at its homepage.

1.4. What mechanism should I use?

In all three mechanisms, you should not use HTML event handler attributes, it is outdated, and is a bad practice as mentioned above.

The remaining two are relatively interchangeable, at least for simpler purposes:

  • Event handler properties are less powerful and optional but are compatible with the browser (IE8 support). You should start with this mechanism if you are learning JS.
  • DOM Level 2 Events (addEventListener (), etc.) is more powerful but also complex and not compatible with many browsers (IE9 support). You should use it when you have experienced.

The main benefit of the third mechanism is that you can delete the event handler code if needed, use removeEventListener() and add multiple listeners with an event to the element if required. For example, you can call addEventListener('click', function() {...}) on an element multiple times with different functions in the second argument. It is not possible with event handler properties for a few things. assignment in subsequent times will overwrite the previous one, for example:

Note: If you are required to support browsers older than Internet Explorer 8 in your work, you may have trouble, because these ancient browsers use different event models from the new browsers. than. But never fear, most JavaScript libraries (eg jQuery) have built-in functions that help eliminate differences between browsers. Don't worry about this too much at this stage in your learning journey.

2. Other event concepts

2.1. Event objects

Sometimes we pass an event handler to an object with a name like event , evt or simply e . It is called an event object and it automatically passes to the event handler to add functions and information. For example:

You can view fullcode at

Note: You can use any name you like for the event object – you just need to choose a name that you can then use to reference it inside the event handler function. e/evt/event are most commonly used by developers because they are short and easy to remember. It's always good to be consistent – with yourself, and with others if possible.

2.2. Event bubbling and capture

The last topic we want to talk about is something you may not see often but it can really panic if you don't understand. Event bubbling and capture and two mechanisms that describe what happens when two handlers for a connected event are triggered in an element. See the following example to understand it:

Extremely simple example shows and hides 1 <div> with <video> inside:

When you click <button> , the video will show the view by changing the class attribute in <div> from hidden to showing:

Then there are 2 more onclick event handlers – 1 for <div> and the second for <video> . The idea is that when the <div> area outside the video is clicked, this box will hide, and when the video click, the video will start running:

But there was a problem – right now, when you click the video to start running but it is also a <div> hidden at the same time. That's because <video> inside the <div> tag, so when you click the video, it actually runs both events.

2.3. Bubbling and capturing explained

When an event is fired from an element, which has parent elements (such as <video> has a <div> tag as a parent), modern browsers will run a different stage: the capturing phase and the bubbling. phase.

In the capturing phase:

  • The browser checks if the nearest <html> (outer-most ancestor) has an onclick event registered in the capture phase and runs it if available
  • It then moves into the next element within <html> and does the same thing, then continues until it reaches the element that is actually clicked.

In the bubbling phase, the exact opposite occurs:

  • The browser will check to see if the component actually clicked has an onclick event handler registered in the effervescent stage, running it if available.
  • It then moves into the ancestral element immediately and does the same, continuing on until the <html> element

In modern browers, by default all event handlers are registered during the effervescent period. So in the current example, when you click a video, the bubbling event from <video> will be directed to the <html> tag. Details will be as follows:

  • It finds video.onclick … handler and runs it so first the video will start playing
  • Then search for videoBox.onclick … handler and run it, so the video will be hidden

2.4. Fixing the problem with stopPropagation()

This is an annoying behavior but there is a way to fix it. The standard Event object has one available function, stopPropagation() , when called in an event object handlers, the first handler will run but the event will not bubble again, so no additional handlers will be run. :

Note: Why do we care both capturing and bubbling? Well, on a bad day, the browser is less compatible than we have now, Netscape only uses event capturing and Internet Explorer only uses event bubbling. When the W3C decided to try to standardize behavior and reach consensus, they ended up with a system that included both, which is a modern browser implemented.

Note: As mentioned above, by default all event handlers are registered in the bubbling phase and this makes more sense for most of the time. If you really want to register an event in phase capturing, you can register your hanlder by using addEventListener () and setting the third option to true.

2.5. Event delegation: Authorize the event

Bubbling also allows us to take advantage of the event delegation – this concept is based on the fact that if you want some code to run when you click on a large number of child elements, you can set the event listener for their parent and there are events that take place in them more frothy than you may have to set the event listener in each child tag. Remember they said earlier that bubbling involves checking the event element triggered for an event handler first that moves up to its parent element?

A good example is multiple lists of items – if you want each of them to display a message when clicked, you can set the click event listener on the parent <ul> tag and the event will bubble from each item to <ul>

Even delegation allows you to avoid adding events to each individual node, instead the event listener is added to a parent tag. The event listener parses from the bubbling event to find child tags. The basic concept is quite simple but many people do not understand how the event delegation works. Let me explain

See the UL code snippet with a few tags:

Now we assign the event to each child tab when clicked. You can add separate event listeners for each individual LI card, but what if LI is often added or deleted? Adding and deleting event listeners will become a nightmare especially when the code adds and deletes in different locations in your application. A good solution to adding an event listener is to add it to the UL parent tag. But if you add the parent tag, do you know which element is clicked?

Simply put: when the event bubbles for the UL element, you will check the target property of the event object to get a reference to the actual clicked node. Here is a basic JavaScrit example that illustrates event delagation :

Start by adding 1 click event listener to the parent tag. When the event listener is enabled, check the event element to make sure it is the type of element being captured. If it's a LI element, boom: that's what I need. If not the element we weighed, the event will be ignored. Extremely simple example -UL and LI are straightforward comparisons. Try something more difficult. Consider the parent DIV tag with many children but we only care about 1 label A with class CSS classA :

You can see the Element.matches API here:

Because most developers use JavaScript libraries to handle events and their DOM elements, I recommend using the library's event authorization method, because they have the ability to define delegates and advanced element.

Hopefully the article is helpful for you about the concepts surrounding event authorization and the convenience surrounding the power of this authorization.


  • There are 3 general ways to assign an event to a DOM element: assign an attribute, assign an inline or use addEventListener()
  • How addEventListener() can assign multiple events to a component, and have a partner, removeEventListener() deletes the assigned event.
  • Also when transmitting events there are many components that are transmitted.
  • You should understand bubbling and capturing in events, DOMs that handle events according to parent and child tags. Besides take advantage of it with Event delegation

Bubbling also allows us to take advantage of the event delegation – this concept is based on the fact that if you want some code to run when you click on a large number of child elements, you can set the event listener for their parent and there are events that take place in them more frothy than you may have to set the event listener in each child tag.


Share the news now

Source : Viblo