Spex3
    

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!");
});


✅ 2. Using the onclick Property (Not Recommended)

button.onclick = function() {
alert("Button clicked!");

};


4️⃣ Removing Event Listeners ❌
To remove an event listener, you need to reference the function:


function greet() {
alert("Hello!");
}

button.addEventListener("click", greet);
button.removeEventListener("click", greet); // Removes the click event


5️⃣ Event Handling Examples 🚀
✅ 1. Click Event

document.getElementById("myButton").addEventListener("click", function() {
console.log("Button was clicked!");
});


✅ 2. Mouseover and Mouseout

let box = document.getElementById("myBox");

box.addEventListener("mouseover", function() {
box.style.backgroundColor = "yellow";
});

box.addEventListener("mouseout", function() {
box.style.backgroundColor = "white";
});


✅ 3. Keydown Event (Detecting Key Presses)

document.addEventListener("keydown", function(event) {
console.log(`Key pressed: ${event.key}`);
});


✅ 4. Form Submit Event (Preventing Default Behavior)

document.getElementById("myForm").addEventListener("submit", function(event) {
event.preventDefault(); // Prevents page reload
console.log("Form submitted!");
});


6️⃣ Summary
✅ Events trigger actions in JavaScript (click, keypress, mouseover, etc.).
✅ Use addEventListener() to attach events (recommended).
✅ Use removeEventListener() to detach events.
✅ Prevent form submission using event.preventDefault().


    Date: 2025-03-29 00:00:00.000000