Events allow executing actions in response to user interactions with a web page, such as pressing a key or moving the mouse. JavaScript uses event listeners to detect these interactions and trigger functions accordingly.
Event listeners are functions attached to an HTML element that trigger when a specific event occurs.
Recommended method:
element.addEventListener("event", function);
Example:
// Adds a listener for click on a button
let button = document.getElementById("myButton");
button.addEventListener("click", function() {
alert("Button clicked!");
});
To listen for a key press or key combination, we often use keydown, keyup, or keypress events.
keydown.document.addEventListener("keydown", function(event) {
if (event.key === "Enter") {
console.log("Enter key pressed");
}
});
You can detect a key combination like Ctrl+C or Shift+A by checking the event.ctrlKey, event.shiftKey and event.altKey properties.
document.addEventListener("keydown", function(event) {
if (event.ctrlKey && event.key === "c") {
console.log("Ctrl + C pressed");
}
});
event.key: returns the pressed key (ex: "a", "Enter").event.code: returns the physical code of the key (ex: "KeyA", "Enter").event.ctrlKey, event.shiftKey, event.altKey: return true if Ctrl, Shift, or Alt keys are pressed.Mouse events allow reacting to movements, clicks, and other cursor interactions.
This example displays the mouse position in the console on each movement.
document.addEventListener("mousemove", function(event) {
console.log("Mouse position: X = " + event.clientX + ", Y = " + event.clientY);
});
You can detect a right click with event.button (0 for left button, 1 for middle button, 2 for right button).
document.addEventListener("mousedown", function(event) {
if (event.button === 2) { // Right button
console.log("Right click detected");
}
});
event.clientX and event.clientY: cursor position relative to the window.event.screenX and event.screenY: cursor position relative to the screen.event.button: mouse button identifier (0: left, 1: middle, 2: right).To remove an event listener, you need to reference the function to remove when calling removeEventListener.
Example:
function showAlert() {
alert("Alert!");
}
let button = document.getElementById("myButton");
button.addEventListener("click", showAlert);
// Remove the event listener
button.removeEventListener("click", showAlert);
Enter.wheel.Event listeners allow capturing user interactions and making web pages dynamic. By combining different types of events (keyboard, mouse), you can create a rich and interactive user experience.