JavaScript Events
An event is something that happens to an HTML element. Events can be initiated by the browser itself or a user interacting with the document. Sometimes we will want to intercept events, which is where JavaScript events come into play.
An event can be captured in JavaScript VIA an attribute on the HTML element or by creating a custom event listener. In this tutorial, we will learn how to use both so you can choose which method is most suitable for your situation.
List of Common JavaScript Events
onchange
- the element has changedonclick
- the user click event on an elementonmouseover
- the user hovers over an elementonmouseout
- the user moves the cursor off an elementonkeydown
- the user presses a keyonload
- the page has finished loading
Adding Event Listeners VIA Attributes
To add an event listener directly on an element create an attribute with the event type and set its contents as the JavaScript to handle the event. This can be a call to a named function or logic in the attribute.
<button onclick="alert('hello')">Click me</button>
Here is another example, except this one uses a named function.
<button onclick="btnClick(this)">Click me</button>
function btnClick(btn) {
console.log(btn.innerText);
}
Creating Event Listeners in Pure JavaScript
Use the addEventListener()
method on an element and pass the type as the first argument and handler as the second.
<button id="foo">Click me</button>
document.getElementById('foo').addEventListener('click', function() {
alert(this.innerText);
});
Read more about how to add event listeners in JavaScript and what can be done with them.
On Page Load Event
A common task is running a JavaScript function only after the DOM has fully loaded. This can be done using the onload
JavaScript event. Let's look at an example of how to do this.
function pageLoaded() {
console.log('page loaded!');
}
window.onload = pageLoaded;