What are Events in JavaScript and How to Handle Them?

Why Use Events

Add Event Handler

const button = document.querySelector("button");
button.addEventListener("click", function (e) {
alert("Button clicked");
});

Can an Event Have More Than One Handler?

Event Object

document.querySelector("input").addEventListener("change", function (e) {
alert(e.target.value);
});

Prevent Default Behavior of the Event

const a = document.querySelector("a.some-link");
a.addEventListener("click", function (e) {
e.preventDefault();
if(confirm("Are you sure?")) {
window.location.href = e.target.href;
}
});

Prevent Other Handlers from Handling this Event

const button = document.querySelector("button");

button.addEventListener("click", function (e) {
e.stopImmediatePropagation();
alert("Hello!");
});

button.addEventListener("click", function (e) {
alert("Bye!")
})

Difference Between preventDefault, stopPropagation, and stopImmediatePropagation

Handle Events on Dynamic Elements

const buttons = document.querySelectorAll(".btn");

buttons.forEach((btn) => {
btn.addEventListener("click", function (e) {
alert("Hello!");
});
})

//create new button
const button = document.createElement('button');
button.classList.add('btn');
button.textContent = "Bye";
document.body.append(button);
document.body.addEventListener("click", function (e) {
if (e.target.classList.contains("btn")) {
alert("Hello!");
}
})

//create new button
const button = document.createElement('button');
button.classList.add('btn');
button.textContent = "Bye";
document.body.append(button);

Remove Event Handler

const button = document.querySelector("button");

function handleClick (e) {
alert("Hello");
}

button.addEventListener("click", handleClick);

//some time later
button.removeEventListener("click", handleClick);

Conclusion

  1. Introduction to Events
  2. Event Reference

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store