About Lesson
Common Event Types and Practical Examples
Different event types are used for various types of interactions. Here are some common events with examples:
click
Occurs when an element, like a button or link, is clicked.
Example:
JavaScript
document.querySelector("#alertButton").addEventListener("click", function() {
alert("You clicked the button!");
});
mouseenter and mouseleave
Triggered when the mouse pointer enters or leaves an element. This is useful for hover effects or tooltips.
Example:
JavaScript
let hoverBox = document.querySelector("#hoverBox");
hoverBox.addEventListener("mouseenter", function() {
hoverBox.style.backgroundColor = "lightblue";
});
hoverBox.addEventListener("mouseleave", function() {
hoverBox.style.backgroundColor = "";
});
In this example, the box changes color when the mouse enters and reverts to the original color when it leaves.
keydown and keyup
Triggered when a key is pressed down or released. Commonly used for handling keyboard shortcuts or detecting key strokes.
Example:
JavaScript
document.addEventListener("keydown", function(event) {
console.log("Key pressed:", event.key); // Logs the key pressed
});
This event listener logs the key the user presses in the console.
submit
Triggered when a form is submitted. Often used with preventDefault() to handle form submissions with JavaScript.
Example:
JavaScript
let form = document.querySelector("form");
form.addEventListener("submit", function(event) {
event.preventDefault(); // Prevents form from actually submitting
alert("Form submission blocked!");
});