Display an alert with “Hello World!” when the user clicks on an element.
element.addEventListener(“click”, function(){ alert(“Hello World!”); }); |
You can also reference an external “named” function.
Trigger an alert with “Hello World!” when the user clicks on an element.
element.addEventListener(“click”, myFunction); function myFunction() { alert (“Hello World!”); } |
The addEventListener() method enables you to attach multiple events to the same element without replacing any existing event listeners.
element.addEventListener(“click”, myFunction); element.addEventListener(“click”, mySecondFunction); |
You can attach different types of events to the same element.
element.addEventListener(“mouseover”, myFunction); element.addEventListener(“click”, mySecondFunction); element.addEventListener(“mouseout”, myThirdFunction); |
The addEventListener() method lets you attach event listeners to any HTML DOM object, including HTML elements, the document, the window, and other objects that support events, like the XMLHttpRequest object.
Attach an event listener that triggers when the user resizes the window.
window.addEventListener(“resize”, function(){ document.getElementById(“demo”).innerHTML = sometext; }); |