What are Events?
An event can be something the user does - like clicking a mouse button, typing on the keyboard, or it can be something generated by APIs, like the completion of a file download operation.
Types of Events
- Mouse Events: click, mouseover, mouseout
- Keyboard Events: keydown, keyup
- Form Events: submit, change
- Document/Window Events: load, resize, scroll
Events are retrieved using keywords for each event. The list and explanation of most events in JavaScript are as follows:
- onAbort - when a certain image fails to load in the browser.
- onBlur - when the input focus is shifted from a form element (when the user clicks outside of a text box, for example).
- onChange - when the user changes the content in text, textarea, or select form elements.
- onFocus - when a form field gets input focus.
- onClick - when a user clicks on an element on the page.
- ondblClick - when a user clicks twice consecutively on a certain element of the page.
- onKeyPress - when the user presses and releases a specific key on the keyboard.
- onKeyUp - when the user releases a specific key on the keyboard.
- onKeyDown - when the user presses a specific key on the keyboard.
- onReset - when the user presses the reset button.
- onResize - when the user changes the size of the web browser window.
- onSelect - when the user selects a form field.
- onSubmit - when the user presses the submit button.
- onLoad - when the web page is loaded in the web browser.
- onUnload - when the user leaves the web page.
- onMouseDown - when the user clicks on the page content.
- onMouseMove - when the user moves the mouse pointer over a certain element of the page.
- onMouseOut - when the user moves the mouse pointer over a certain element of the page.
- onMouseOver – when the user leaves the mouse pointer over a certain element of the page.
- onMouseUp - when the user releases the left mouse button while the mouse pointer is on a certain element of the page.
In the following example, a function displayMessage() is created that is printed on a button click.
<!DOCTYPE html>
<html>
<body>
<button id="myButton" onclick='displayMessage()'>Button</button>
<p id="paragraph"></p>
<script>
function displayMessage() {
document.getElementById("paragraph").innerHTML = 'Hello from JavaScript';
}
</script>
</body>
</html>
Handling Events
There are several ways to handle events in JavaScript:
Inline Event Handlers
You can add event handlers directly within your HTML elements.
<script>
<button onclick="alert('Button clicked!')">Click Me!</button>
</script>
In the real world, inline events are rarely used, since they require that you write JavaScript directly in HTML.
Event Handler Properties
Assign a function to the event handler property of the DOM element.
<script>
const button = document.getElementById('myButton');
button.onclick = function() {
alert('Button clicked!');
};
</script>
addEventListener()
The most flexible way to handle events is addEventListener(). It allows you to add many events to the same element, and more control over how the event is handled.
<script>
const button = document.getElementById('myButton');
button.addEventListener('click', function() {
alert('Button clicked!');
});
</script>
Event Object
Whenever an event occurs, an event object is created. This object contains all the information about the event, including the element that triggered the event, the type of event, and other specific information like the mouse position for mouse events.
<script>
button.addEventListener('click', function(event) {
console.log(event.type); // Will output: click
});
</script>
Custom Events
Custom events are a way to create your own events that can be dispatched and listened to just like built-in events.
Creating a Custom Event
To create a custom event, you use the CustomEvent constructor.
<script>
const myEvent = new CustomEvent('myCustomEvent', {
detail: { message: 'This is a custom event' }
});
</script>
Dispatching Custom Events
To trigger the event, use the dispatchEvent method on an element.
<script>
const button = document.getElementById('myButton');
button.dispatchEvent(myEvent);
</script>
Listening for Custom Events
You listen to custom events in the same way you listen to any other event.
<script>
button.addEventListener('myCustomEvent', function(e) {
console.log(e.detail.message); // Will output: This is a custom event
});
</script>
Events are a fundamental part of interactive web applications in JavaScript. Understanding how to handle built-in events and create custom events allows you to make dynamic and user-friendly web pages. With addEventListener and CustomEvent, you have the tools needed to effectively respond to and create a wide range of events.
Working with Events
In this example, let's create an interactive web page where users can click a button to load user data from an API. We'll use JavaScript events to handle the button click, make an API request, and then use a custom event to process and display the data.
HTML Setup
First, we need an HTML structure with a button and a div to display the user data.
<!DOCTYPE html> <html> <head> <title>JavaScript Events Example</title> </head> <body> <button id="loadButton">Load User Data</button> <div id="userData"></div> <script src="script.js"></script> </body> </html>
JavaScript: Handling Click Events and Making API Requests
document.getElementById('loadButton').addEventListener('click', function() { fetch('https://jsonplaceholder.typicode.com/users/1') .then(response => response.json()) .then(userData => { const userDataEvent = new CustomEvent('userDataLoaded', { detail: userData }); document.dispatchEvent(userDataEvent); }) .catch(error => console.error('Error loading user data:', error)); });
In script.js, we'll add the JavaScript to handle the button click event and make an API request to fetch user data.
Using Custom Events to Process and Display Data
We'll listen for the userDataLoaded custom event and use it to display user data.
document.addEventListener('userDataLoaded', function(e) { const userData = e.detail; const displayDiv = document.getElementById('userData'); displayDiv.innerHTML = `<h3>User Data</h3><p>Name: ${userData.name}</p><p>Email: ${userData.email}</p>`; });
In this example, we have a button for loading data and a div for displaying the user data. When the button is clicked, an API request is made to fetch user data. We use the Fetch API to make an asynchronous request to get user data. This is a common task in web applications.
Once the data is loaded, we create a custom event (userDataLoaded) and dispatch it, passing the user data in the event's detail property. Another listener is set up to respond to our custom event. When the event is triggered, it updates the HTML of userData div to display the loaded user data.
This example demonstrates how to work with both built-in and custom events in a real-world scenario. It shows event handling for user interactions and dynamic content loading, common requirements in modern web applications.