Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

Add an Event Handler to an Element

Example

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.

Example

Trigger an alert with “Hello World!” when the user clicks on an element.

element.addEventListener(“click”, myFunction);

function myFunction() {
  alert (“Hello World!”);
}

Add Many Event Handlers to the Same Element

The addEventListener() method enables you to attach multiple events to the same element without replacing any existing event listeners.

Example

element.addEventListener(“click”, myFunction);
element.addEventListener(“click”, mySecondFunction);

You can attach different types of events to the same element.

Example

element.addEventListener(“mouseover”, myFunction);
element.addEventListener(“click”, mySecondFunction);
element.addEventListener(“mouseout”, myThirdFunction);

Add an Event Handler to the window Object

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.

Example

Attach an event listener that triggers when the user resizes the window.

window.addEventListener(“resize”function(){
  document.getElementById(“demo”).innerHTML = sometext;
});