Gyaan

Event Bindings

beginner DOM events

Whenever we want to bind any event with the HTML element then we use addEventListener() or onclick attribute of the HTML element. This is called Event Binding.

document.getElementById('button').addEventListener("click", () => {
  console.log("clicked");
});

document.getElementById('button').onclick = () => {
  console.log("clicked");
}

The main difference between the two is that addEventListener() allows multiple handlers on the same event, while onclick replaces the previous handler.

const btn = document.getElementById('button');

// addEventListener - both handlers will fire
btn.addEventListener("click", () => console.log("first"));
btn.addEventListener("click", () => console.log("second"));
// Click → "first" then "second"

// onclick - second handler replaces the first
btn.onclick = () => console.log("first");
btn.onclick = () => console.log("second");
// Click → "second" only

addEventListener() also accepts a third parameter for options like capture, once, and passive.

To remove a bound event, we use removeEventListener() with the same function reference. This is why we should store the handler in a variable instead of writing an anonymous function directly.

function handleClick() {
  console.log("clicked");
}

btn.addEventListener("click", handleClick);
btn.removeEventListener("click", handleClick); // works

btn.addEventListener("click", () => console.log("clicked"));
btn.removeEventListener("click", () => console.log("clicked")); // does NOT work, different reference