The goal of this tutorial is to introduce you to the common types of events in JavaScript and how to use them. By the end of this tutorial, you'll understand what JavaScript events are, how they work, and how to utilize them in your web applications.
This tutorial assumes you have basic knowledge of HTML, CSS, and JavaScript, including variables, functions, and DOM manipulation.
JavaScript events are "things" that happen to HTML elements. When these "things" actually happen, they can be used to trigger JavaScript code. Some common types of events include:
mousemove
, mouseover
, mouseout
, mousedown
, mouseup
etc.keydown
, keyup
, keypress
etc.submit
, change
, focus
, blur
etc.JavaScript provides the addEventListener
method to attach an event to an HTML element.
Here's the general syntax:
element.addEventListener('event', function);
Let's break it down:
element
is the HTML element you want to add an event to.event
is the type of the event (like click
, load
, mouseover
, etc.).function
is the function to be executed when the event occurs.addEventListener
method to attach events as it allows you to add multiple events to the same element.load
event as it can slow down your website if you have heavy scripts running on load.form
events to protect your website from malicious input.// Select the button element
var button = document.querySelector('button');
// Add a click event to the button
button.addEventListener('click', function() {
alert('Button was clicked!');
});
When you click the button, an alert box will appear on the page saying "Button was clicked!".
// Add a load event to the window
window.addEventListener('load', function() {
console.log('Page is fully loaded');
});
When you refresh the page, "Page is fully loaded" will be logged to the console.
In this tutorial, we covered the different types of JavaScript events and how to use them. To continue learning, try adding different types of events to different HTML elements and see what you can do with them.
Solution:
// Select the button and paragraph elements
var button = document.querySelector('button');
var paragraph = document.querySelector('p');
// Add a click event to the button
button.addEventListener('click', function() {
paragraph.textContent = 'Hello, World!';
});
When you click the button, the text of the paragraph changes to "Hello, World!".
Solution:
// Add a mousemove event to the window
window.addEventListener('mousemove', function(e) {
console.log('X: ' + e.clientX + ', Y: ' + e.clientY);
});
When you move your mouse, the x and y coordinates of the mouse will be logged to the console.