JavaScript Events 🎭

JavaScript Events 🎭
Events allow JavaScript to respond to user actions (clicks, typing, mouse movement, etc.).
1️⃣ What are Events?
Events occur when users interact with a webpage, such as:
Clicking a button (click).
Hovering over an element (mouseover).
Pressing a key (keypress).
2️⃣ Common Browser Events 📌
✅ Mouse Events
Event Description
click Fires when an element is clicked.
dblclick Fires when an element is double-clicked.
mouseover Fires when the mouse enters an element.
mouseout Fires when the mouse leaves an element.
mousemove Fires when the mouse moves over an element.
mousedown Fires when a mouse button is pressed.
mouseup Fires when a mouse button is released.
✅ Keyboard Events
Event Description
keydown Fires when a key is pressed down.
keyup Fires when a key is released.
keypress (Deprecated) Fires when a key is pressed.
✅ Form Events
Event Description
submit Fires when a form is submitted.
change Fires when a form element value changes.
focus Fires when an input field is focused.
blur Fires when an input field loses focus.
✅ Window Events
Event Description
load Fires when a page is fully loaded.
resize Fires when the browser window is resized.
scroll Fires when the page is scrolled.
3️⃣ Adding Event Listeners 🎯
✅ 1. Using addEventListener() (Recommended)
let button = document.getElementById("myButton");
button.addEventListener("click", function() {
alert("Button clicked!");
});
button.onclick = function() {
alert("Button clicked!");
};
function greet() {
alert("Hello!");
}
button.addEventListener("click", greet);
button.removeEventListener("click", greet); // Removes the click event
document.getElementById("myButton").addEventListener("click", function() {
console.log("Button was clicked!");
});
let box = document.getElementById("myBox");
box.addEventListener("mouseover", function() {
box.style.backgroundColor = "yellow";
});
box.addEventListener("mouseout", function() {
box.style.backgroundColor = "white";
});
document.addEventListener("keydown", function(event) {
console.log(`Key pressed: ${event.key}`);
});
document.getElementById("myForm").addEventListener("submit", function(event) {
event.preventDefault(); // Prevents page reload
console.log("Form submitted!");
});
Date: 2025-03-29 00:00:00.000000