addEventListener()

addEventListener is a method used to attach event listeners to HTML elements. It allows you to specify which event (e.g., "click," "keydown") you want to listen for and what action to perform when that event occurs. Event listeners are used to create interactivity in web pages, responding to user actions like clicks or key presses. addEventListener is a versatile way to handle events, and it supports attaching multiple event listeners to a single element, making it a fundamental part of web development for creating dynamic and responsive web applications.


const outerDiv = document.getElementById("outerDiv");
const innerDiv = document.getElementById("innerDiv");

//both elements are waiting for click while sharing some space with each other
outerDiv.addEventListener("click", changeWhite, true); //third argument - 'true' makes outerDiv preffered and it is first to change onclick
innerDiv.addEventListener("click", changeWhite);

function changeWhite() {
  alert(`You have changed ${this.id} element to white`);
  this.style.backgroundColor = "white";
}