Handling events in JavaScript

JavaScript

0 Comments

When something happens on the page (like a mouse click, key press, or mouse movement), an event is fired. We can listen for these events and do something when they happen.

Example

function setupButton() {
    var myButton = document.querySelector('#myButton');

    /* When the button is clicked, run our showAlert function */
    myButton.addEventListener('click', showAlert);
}

function showAlert() {
    alert('This is an alert');
}

// Run our setupButton function
setupButton();

On line 5, we tell the browser to run our showAlert function whenever someone clicks myButton. Technically, clicking the button causes its click event to fire, and this is what we're listening for.

Common JavaScript events

click
This event fires whenever an element is clicked.
change
Fires whenever an element changes (like an <input> box).
keydown
Fires whenever a keyboard key is pressed.
DOMContentLoaded
Fires when all the HTML tags have been parsed and the DOM is ready to be accessed through JavaScript.
load
Fires whenever the page (or an element) is fully loaded.
beforeunload
Fires before the page is unloaded (closed).
mouseover
Fires whenever the mouse moves over an element.
mouseout
Fires whenever the mouse moves away from an element.

There are many other events that are available. For the full list, see this page.

Leave a Comment