Skip to content

Javascript. Events

Maria Barros edited this page Jan 17, 2019 · 1 revision

Events represent any event that take place in the DOM. Each event contains properties and methods.

We are going to use the most common way to respond to an event: the addEventListener method. addEventListener has two arguments: the event's type and a callback function.

Event listener for a button

//Getting the button by element id                          ` 
const clickableButton = document.getElementById("button1");
  if (clickableButton){
	// Use the same function for responding to click and focus events
	clickableButton.addEventListener("click", btnEventListener);
	clickableButton.addEventListener("focus", btnEventListener);

	function btnEventListener(e){
		console.log(e.type);
                e.stopPropagation();
		// You also can remove the event listener
		clickableButton.removeEventListener(e.type);
	}	
}

Event listener for a form

// Event listener for a form
// Getting a form by element id 
const myForm = document.getElementById("myForm");
if(myForm){
	myForm.addEventListener("submit", formEventListener)

	function formEventListener(e){
		e.preventDefault();
	}

}

Event listener for the DOM content loaded

// Event listener for a DOM content loaded
document.addEventListener("DOMContentLoaded", contentLoaded);

function contentLoaded(){
	console.log("DOM Content loaded");
}

The DOMContentLoaded event might be trigger before elements like images are loaded. That's why we have to define event listener functions for load events in the window object.

window.addEventListener("load", checkImages);

function checkImages(){
	const myImage = document.getElementById("myImage");
	console.log(myImage.offsetWidth, myImage.offsetHeight);
}