DOM events in JavaScript

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:

 event.addEventListner(‘click’ , callback , true)

This time, instead of using the “onclick” 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 “onclick” can be inserted into most HTML elements to respond to that tag’s onclick action, something like “onload” only works inside the <body> and <img> tags.

It is best practice to create named event handler function instead of anonymous functions. This way your code will remain organised.

Here is an example of named event handler function:

Example of named event handler function

The addEventListener() is an inbuilt JavaScript function which takes the event to listen for, and a second argument to be called whenever the described event gets fired. Any number of event handlers can be added to a single element without overwriting existing event handlers.

Also, you can easily remove an event listener by using the removeEventListener() method.

Some of the features of the event listener method include:

  • The addEventListener() method attaches an event handler to the specified element.
  • This method attaches an event handler to an element without overwriting existing event handlers.
  • You can add many event handlers to one element.
  • You can add many event handlers of the same type to one element, i.e two “click” events.
  • Event listeners can be added to any DOM object not only HTML elements. i.e the window object.
  • The addEventListener() method makes it easier to control how the event reacts to bubbling.

When using the addEventListener() method, the JavaScript is separated from the HTML markup, for better readability and allows you to add event listeners even when you do not control the HTML markup.

Passing Event as a Parameter

Sometimes we want to know more information about the event when it was clicked. For that we have to pass an event parameter to our function.

Let’s see an example how we can implement this.

button.addEventListener('click', (e)=>{
console.log(e.target.id)
})

From the above example, the event parameter is a variable named e but it can easily called anything else such as event. This is a parameter of an object contains various information about the event such as target id.

For example when a KeyboardEvent happens, you can check which key was pressed, in a readable format (Escape, Enter and so on) by checking the key property:

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

What’s the difference?

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.

const button = document.querySelector(".btn");
button.addEventListener("click", event => {
console.log("Hello!");
});
button.addEventListener("click", event => {
console.log("How are you?");
})
// This wil log
// "Hello!"
// "How are you?"
// to the console

In the example above, the “onclick” 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.

   const button = document.querySelector(".btn");   button.addEventListener("click", event => {
console.log("Hello!");
})
button.addEventListener("click", event => {
console.log("How are you?");
})
// This wil log
// "Hello!"
// "How are you?"
// to the console

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.

Event Bubbling

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

event.addEventListner('click' , callback , true)

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:

Get a <li> elements index value on click with jQuery

source: https://www.deanpugh.com/get-a-li-elements-index-value-on-click-with-jquery/

jQuery find() traverse downwards along descendants of DOM elements, all the way down to the last descendant. To only traverse a single level down the DOM tree (to return direct children), use the children() method.

A descendant is a child, grandchild, great-grandchild, and so on.
Siblings share the same parent.

$(document).ready(function(){
$(“ul”).find(“span”).css({“color”:“red”, “border”:“2px solid red”});
});

how to detect which button is clicked using jQuery

$("input").click(function(e){
var idClicked = e.target.id;
});

Set image src to another image jquery

Change the src of the image, not of the div:

$('#img-wrapper img').attr("src",loc);

Experience with Front-end Technologies and MERN / MEAN Stack. Working on all Major UI Frameworks like React, Angular.