There are three methods to add event listener to HTML:
The first method is usually the best (The two other are cover at the end).
This is usually the best method.
<button id="btn">Click Me Too</button>
const btn = document.querySelector("#btn");
btn.addEventListener("click", () => {
alert("Hello!");
});
Use .querySelectorAll and then add the listener on that element. Then the
forEach keyword.
const buttons = document.querySelectorAll("button");
buttons.forEach(btn => btn.addEventListener("click", () => {
alert("Hello");
}));
Regardless of the methods used, a named function can be used instead of an arrow function.
function myFunction() {
console.log("Hello");
}
btn.addEventListener("click", myFunction);
Regardless of the methods used, the event can be passed as argument in the function called.
It passes an object that references the event itself.
It gives access to properties and methods such as the key pressed, or the DOM node clicked…
btn.addEventListener("click", function (e) {
console.log(e.target);
e.target.style.background = "blue";
});
| event | description |
|---|---|
| click | |
| dblclick | double click |
| keydown | |
| keyup |
<button id="btn">Click Me</button>
const btn = document.querySelector('#btn');
btn.onclick = () => alert("Hello World");
Note: can only add one event listener
<button onclick="functionName()">Click here</button>
Note: not ideal because cluttering the HTML.