JS DOM - 03.02 - Events Handlers

Handlers are functions that run js code in case of user actions using events.

Three ways of doing this

  • HTML-attribute: Specify function attributes directly on the HTML elements
  • DOM Property: Set properties in the form of on<eventType>, such as onClick or onmousedown on the DOM nodes in the JavaScript
  • Attach event listeners to the DOM nodes in your JavaScript

Event Listeners are the preferred method

Method 1: HTML-attribute

<button onclick="alert('Hello World!')">Click Me</button>

<input type="button" value='Click me' onclick="alert('Click!')">

Using it with named functions to reduce code in HTML file

<button onclick="alertFunction()">Click Me</button>
function alertFunction() {
	alert("Yay you cliked");
}

It clutters the HTML with JavaScript. Also it has one onclick property per DOM element, so no multiple separate functions.

HTML attributes names are not case-sensitive, so ONCLICK works as well but usually it is kept all lower cased. But DOM properties are case-sensitive.

Method 2: DOM property

We can assign a handler using DOM property.

<button id="btn">Click Me</button>
const btn = document.querySelector("#btn");
btn.onclick = () => alert("Hello World");

js is out but still DOM element can only have one onclick property. No more than one handler can be assigned.

Using a named function

<button id="btn">Click Me</button>
function alertFunction() {
	alert("Yay you clicked");
}

btn.onclick = alertFunction;
// no () for the function call

if () is used, the value of function gets assigned to onclick instead of being called.

Method 3: addEventListener()

element.addEventListener(event, handler, [options]);

additional optional object with properties:

  • once: if true, then the listener is automatically removed after it triggers.
  • capture: the phase where to handle the event.
  • passive: if true, then the handler will not call preventDefault()
<button id="btn">Click Me</button>
const btn = document.queryselector("#btn");
btn.addEventListener("click", () => {
	alert("Hello World");
});

This maintains a separation of concerns and we follow multiple event listeners if need arises.

<button id="btn">Click Me</button>
function alertFunction() {
	alert("Yay you clicked");
}

btn.addEventListener("click", alertFunction);

btn.addEventListener("click", function(e) {
	console.log(e);
});

removing event listener

element.removeEventListener(event, handler, [options]);

To remove a handler, same exact function should be passed. not another function with same code. So the handler function has to be stored in a variable, otherwise it cannot be removed.

// this wont work
elem.addEventListener( 'click', ()=> alert('thanks') );
elem.removeEventListener( 'click', ()=> alert('thanks') );

Event object

When an event happens, the browser creates an event object, puts details into it and passes it as an argument to the handler.

Some properties of event object: event.type here it’s a "click".

event.currentTarget Element that handled the event. That’s exactly the same as this, unless the handler is an arrow function, or its this is bound to something else, then we can get the element from event.currentTarget.

event.clientX / event.clientY Window-relative coordinates of the cursor, for pointer events.

elem.onclick = function(event) {
	alert( `${event.type} at ${event.currentTarget}` );
	alert( `Coordinates: ${event.clientX} : ${event.clientY}` );
}