JavaScript events allow you to make your website interactive.
An event happens when a user does something like clicking, typing, or submitting a form.
👉 Example:
- Click → event
- Typing → event
- Hover → event
🖱️ 1. Mouse Events
These events happen when the user uses the mouse.
Common Mouse Events:
click→ when button is clickeddblclick→ double clickmouseover→ when mouse enters elementmouseout→ when mouse leaves element
Example:
<button onclick="showMessage()">Click Me</button><script>
function showMessage() {
alert("Button clicked!");
}
</script>
⌨️ 2. Keyboard Events
These events happen when user types on keyboard.
Common Keyboard Events:
keydown→ key pressedkeyup→ key releasedkeypress(old, avoid now)
Example:
<input type="text" onkeyup="checkInput()"><script>
function checkInput() {
console.log("User is typing...");
}
</script>
📝 3. Form Events
These events are used in forms.
Common Form Events:
submit→ when form is submittedchange→ when input value changesfocus→ when input is selectedblur→ when input loses focus
Example:
<form onsubmit="handleSubmit(event)">
<input type="text" required>
<button type="submit">Submit</button>
</form><script>
function handleSubmit(e) {
e.preventDefault(); // stop page reload
alert("Form submitted!");
}
</script>
🔄 4. Event Bubbling
Event bubbling means:
👉 Event starts from child element → goes up to parent
Example:
<div onclick="parentClick()" style="padding:20px; background:lightblue;">
<button onclick="childClick()">Click Me</button>
</div><script>
function parentClick() {
alert("Parent clicked");
}function childClick() {
alert("Button clicked");
}
</script>
👉 When you click button:
- Button event runs
- Then parent event runs
Stop Bubbling:
function childClick(event) {
event.stopPropagation();
alert("Only button clicked");
}
🎯 5. Event Delegation
Event delegation means:
👉 Instead of adding events to many elements,
you add one event to parent
Why use it?
- Better performance
- Works for dynamic elements
Example:
<ul id="list">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul><script>
document.getElementById("list").addEventListener("click", function(e) {
if (e.target.tagName === "LI") {
alert(e.target.innerText);
}
});
</script>
👉 One event handles all <li> items
🧪 Practice Tasks
✅ 1. Interactive Button
<button id="btn">Click Me</button><script>
document.getElementById("btn").addEventListener("click", function() {
this.innerText = "Clicked!";
});
</script>
✅ 2. Keyboard Typing Detector
<input type="text" id="inputBox" placeholder="Type something"><p id="output"></p><script>
document.getElementById("inputBox").addEventListener("keyup", function(e) {
document.getElementById("output").innerText =
"You typed: " + e.target.value;
});
</script>
💡 Pro Tips (Important for Interviews)
- Use
addEventListener()instead of inline events - Use
eventobject (e) for advanced control - Avoid
keypress(deprecated) - Use event delegation in dynamic apps (like lists, tables)






