DOM event listener

Here is how’s your DOM structured in the browser.

Registering Event Handlers:

An event handler function is registered as a property attached to the DOM element being interacted with.

There are basically 2 ways to register an event.

  1. Using INLINE event handlers-> This approach is highly discouraged.

The basic syntax of these INLINE event handlers is:

OR

2. Using addEventListener[]-> This is the modern way. This method allows to register as many handlers as we need, and it’s the most popular you will find.

Syntax is:

This time, instead of using the “ title” property, we add an event listener that will trigger on the “click” event, after which it logs “Hello!”.

The event handler can also be registered as an HTML element but it is recommended to avoid inline JavaScript.

Different event handlers are used with different HTML elements. For example, while “ title” can be inserted into most HTML elements to respond to that tag’s title action, something like “onload” only works inside the and

On a mouse event we can check which mouse button was pressed:

There’s a subtle, but important difference between these 2 methods of handling events.

If you’ll use the first method, event handlers, the difference is that if you add two event handlers for the same button click, the second event handler will overwrite the first and only that event will trigger.

Which takes us to the main learning:

For a given element, you can only have one event handler per event type, but you can have multiple event listeners.

That’s the key difference. So what does this look like?

Here, the second event handler will overwrite the first one.

In the example above, the “ title” event handler is used twice.

That way, the first one will be overwritten and when a user clicks the button, it will log “How are you?” to the console.

So what happens when we use “addEventListener”?

Using event listeners, we can call multiple functions when a user clicks on the button.

In the example above, we add multiple event listeners to the button.

This way, when a user clicks it, it will trigger both functions and log “Hello! How are you?” to the console.

By default, events bubble in JavaScript. Event bubbling is when an event will traverse from the most inner nested HTML element and move up the DOM hierarchy until it arrives at the element which listens for the event. This move is also popularly known as Event Propagation or Event Delegation.

Now, Suppose we have a event handler like

Last argument is for

True : capture event on Event Capturing Cycle.

False : capture event on Event Event Bubble cycle.

Stop Propagation

An event on a DOM element will be propagated to all its parent elements tree, unless it’s stopped.

A click event on a will propagate to section and then body.

You can stop the propagation by calling the stopPropagation[] method of an Event, usually at the end of the event handler:

Video liên quan

Chủ Đề