Events are at the heart of most pages utilizing JavaScript. For our JavaScript to perform an action, we must wait for a specific event to happen, and then execute the predefined action.
While it was hinted at earlier, events are things that happen on the page. The majority of events utilized in JavaScript applications are user-driven, like: clicking a button, hovering over an element, and pressing a key. However, there are many other events that the browser fires, like: loading all of the resources on a page or going offline. MDN has a good reference of available DOM events.
Now that we have a basic understanding of what DOM events are, we can perform an action when an event occurs.
There are two general ways that we can perform an action when an event occurs: inline event handlers
and event listeners
.
An example of using an inline event handler is like so:
<button id="myButton" onclick="alert('This is bad');">Click Me!</button>
As you probably guessed from reading what was within the alert
- using inline event handlers is a bad practice that we don't recommend.
Instead, it's best to separate your markup from your logic by using event listeners.
An example of using an event listener is like so:
<button id="myButton">Click Me!</button>
var element = document.getElementById('myButton');
element.addEventListener('click', function() {
alert("This is good!");
}, false)
Like mentioned in the previous section, using event listeners have several advantages, such as: separating the markup (HTML) from the behavior (JavaScript) and not duplicating code. This is what people mean by using Unobtrusive JavaScript: it stays separate from your markup and doesn't repeat itself.