Welcome To My Website

DOM Event Listeners

Almost all interactions on a webpage creates an event. When an event occurs, it can trigger a function and using DOM you can manipulate the content of the webpage. There are several different typese of events that can occur on a webpage: user interface (UI), keyboard, mouse, etc. When these events have occurred they are considered to have been fired, after which they can trigger a function in your JavaScript. Now, let's take a look at the 'click' event.

I've created a button for us to click, go ahead and click it, it does nothing: . When you click the button you're literally creating the 'click' event. Now we need to write code that responds to that event. Here's another button for you to click: . You should've gotten an alert saying "HEY!!!". That's because I wrote a function that triggers when the button is clicked.

We want to make sure the page is completely loaded before running our code, otherwise the code will try to run immediately. So all the code we want to use must go inside a 'load' event listener.

	window.addEventListener("load", function(){
		// Put ALL of your JS code inside this function
	});		
		

Look at the parameters for event listeners.

	element.addEventListener('event', functionName);
		

I set up a DOM element, then target the node in the listener. I choose the 'click' event and run a function that shows an alert saying "HEY!!!"

	function itWorks(){
		alert("HEY!!!");
		console.log(itWorks);
	}

	var coolButton = document.getElementById("coolButton");
	coolButton.addEventListener("click", itWorks);
		

There are two other ways to bind an event to an element. HTML event handlers (don't do this), and traditional DOM event handlers. The latter is supported on older browsers but is limited to one function per handler.

:)