Follow This Blog For more... 😊

All About JavaScript Events!

🧠 All About JavaScript Events – A Complete Guide with Examples

JavaScript events are at the heart of interactive web pages. Whether you're clicking a button, hovering over an image, typing into a form, or submitting it — events are what make the page respond to your actions.

In this comprehensive and engaging guide, we'll walk you through:

  • What JavaScript events are
  • Types of events
  • Event listeners
  • Event propagation
  • event object
  • preventDefault() and stopPropagation()
  • Common use cases
  • Plenty of examples

Let’s dive in! 🌊


✅ What is a JavaScript Event?

An event is an occurrence or an action that takes place in the browser, such as:

  • A mouse click
  • A keypress
  • A page load
  • A form submission
  • A user hovering over an element

JavaScript lets you "listen for" and "respond to" these events with code.


🔥 Types of JavaScript Events

Here are some of the most common event types grouped by category:

🔹 Mouse Events

Event Triggered When
click Element is clicked
dblclick Element is double-clicked
mouseenter Mouse enters the element
mouseleave Mouse leaves the element
mousedown Mouse button is pressed
mouseup Mouse button is released
mousemove Mouse moves within an element

🔹 Keyboard Events

Event Triggered When
keydown Key is pressed
keyup Key is released
keypress (Deprecated) Key is pressed (excluding modifier keys)

🔹 Form Events

Event Triggered When
submit A form is submitted
change Value of an input/select/textarea changes
input When user types (on input fields)
focus An input gets focus
blur An input loses focus
reset A form is reset

🔹 Window Events

Event Triggered When
load Page is fully loaded
resize Window is resized
scroll Page is scrolled
unload Page is closed or navigated away from

👂 How to Listen to Events?

You can listen to events using:

1. HTML Event Attributes (Not Recommended for Modern Development)

<button onclick="sayHello()">Click Me</button>

<script>
  function sayHello() {
    alert("Hello!");
  }
</script>

2. element.onclick = function

const btn = document.getElementById("myBtn");
btn.onclick = function () {
  alert("Button clicked!");
};

3. .addEventListener() ✅ Best Practice

const btn = document.getElementById("myBtn");
btn.addEventListener("click", function () {
  alert("Using addEventListener!");
});

You can also remove a listener using:

btn.removeEventListener("click", callbackFunction);

🎯 Event Object (event)

Every event listener receives an event object that contains detailed information about the event.

btn.addEventListener("click", function (e) {
  console.log(e.type);       // click
  console.log(e.target);     // the element clicked
  console.log(e.clientX);    // mouse X position
});

🔁 Event Propagation: Bubbling vs Capturing

🔸 Bubbling (default) – from child to parent

🔸 Capturing – from parent to child

Example:

<div id="parent">
  <button id="child">Click Me</button>
</div>
document.getElementById("parent").addEventListener(
  "click",
  () => alert("Parent clicked"),
  false // bubbling
);

document.getElementById("child").addEventListener(
  "click",
  () => alert("Child clicked"),
  false
);

👉 Output when button clicked:

  • Child clicked
  • Parent clicked (because bubbling)

You can stop bubbling using:

e.stopPropagation();

🚫 event.preventDefault()

Some elements have default behaviors (like links, form submits). To stop them:

document.querySelector("form").addEventListener("submit", function (e) {
  e.preventDefault(); // prevents page refresh
  console.log("Form submitted via JS!");
});

💡 Event Delegation (Advanced Pattern)

Rather than attaching events to every child element, you attach a single event to a common parent.

<ul id="list">
  <li>Item 1</li>
  <li>Item 2</li>
</ul>
document.getElementById("list").addEventListener("click", function (e) {
  if (e.target.tagName === "LI") {
    alert("You clicked " + e.target.innerText);
  }
});

✅ Saves performance and works even with dynamically added elements!


🎉 Real-World Example: Toggle Dark Mode

<button id="toggle">Toggle Theme</button>

<script>
  const btn = document.getElementById("toggle");
  btn.addEventListener("click", () => {
    document.body.classList.toggle("dark-mode");
  });
</script>

<style>
  .dark-mode {
    background-color: #121212;
    color: white;
  }
</style>

🧪 Quick Practice

Try implementing these:

  • Show alert when the mouse enters an image
  • Log the keys user types into an input
  • Prevent form submission and show a custom message
  • Highlight every clicked <li> from a list

📝 Summary

Concept Description
Events User/browser actions you can respond to
.addEventListener Best way to attach events
Event Object Info like target, type, position, etc.
preventDefault() Stops default behavior (e.g., form submit)
stopPropagation() Prevents bubbling
Event Delegation Efficiently handle many child events via parent

🙌 Final Thoughts

JavaScript events bring life to your webpages. Understanding them well is critical to becoming a professional web developer. Once you're comfortable with events, you can build responsive UIs, custom form behavior, interactive games, and more!

Want to go further? Practice building:

  • A todo list with event delegation
  • A form validator with submit, blur, input events
  • A custom context menu using contextmenu and click

Let me know if you want a visual cheat sheet for all JS events! Would you like that?

Comments

Popular Posts