JavaScript recognizes various event types, each corresponding to different user interactions or browser actions. While there are many specific event types, they can be broadly categorized into several groups. Below are some of the major categories, along with notable examples.
Mouse events are the most common and are triggered by user interactions involving a mouse or a similar pointing device.
Key events in this category include:
Fired when an element is clicked.
element.addEventListener('click', function(event) { console.log('Element clicked!'); });
Occurs on a double-click on an element.
element.addEventListener('dblclick', function(event) { console.log('Element double-clicked!'); });
Triggered when the mouse pointer enters the element's area.
element.addEventListener('mouseover', function(event) { console.log('Mouse over element!'); });
Fires when the mouse pointer leaves the element's area.
element.addEventListener('mouseout', function(event) { console.log('Mouse out of element!'); });
Keyboard events are essential for capturing user input from the keyboard. These include:
Fired when a key is pressed down.
document.addEventListener('keydown', function(event) { console.log(`Key pressed: ${event.key}`); });
Triggered when a key is released.
document.addEventListener('keyup', function(event) { console.log(`Key released: ${event.key}`); });
Occurs when a key is pressed and released.
document.addEventListener('keypress', function(event) { console.log(`Key pressed and released: ${event.key}`); });
Form events are crucial in managing user interactions within form elements. They include:
Triggered when a form is submitted.
form.addEventListener('submit', function(event) { event.preventDefault(); // to prevent form submission console.log('Form submitted!'); });
Occurs when the value of an input, select, or textarea element is changed.
input.addEventListener('change', function(event) { console.log('Input value changed!'); });
Fired when an element receives focus.
input.addEventListener('focus', function(event) { console.log('Element focused!'); });
Triggered when an element loses focus.
input.addEventListener('blur', function(event) { console.log('Element lost focus!'); });
Window events are associated with the browser window and include:
Fired when the entire page, including all dependent resources like stylesheets and images, is fully loaded.
window.addEventListener('load', function(event) { console.log('Page fully loaded!'); });
Occurs when the browser window is resized.
window.addEventListener('resize', function(event) { console.log('Window resized!'); });
Triggered when scrolling occurs in the window.
window.addEventListener('scroll', function(event) { console.log('Scrolled!'); });
These examples provide a basic introduction to handling different types of events in JavaScript. For a comprehensive list of events, the Mozilla Developer Network (MDN) provides an extensive guide.