Skip to main content

Command Palette

Search for a command to run...

πŸ“˜ JavaScript Event Handling

Updated
β€’4 min readβ€’View as Markdown
πŸ“˜ JavaScript Event Handling
S

Full Stack Developer Intern at DevSync

Presented by Swapnil Meshram within mentorship Devsync

πŸŽ“ Started learning JavaScript with the guidance of Devsync, focusing on concepts of events and event handling with simple hands-on practice.

πŸ“Œ 1. What is an event in JavaScript?

An event is an action that happens in the browser, triggered by the user or the browser itself.

πŸ”Ή Examples:

  • A user clicks a button

  • A user types in a form

  • A page loads

  • A mouse moves, or a key is pressed


πŸ“Œ 2. What is event handling?

Event handling means writing JavaScript code that listens for these events and responds when they happen.

πŸ‘‰ Example: Show an alert when a button is clicked.


πŸ“Œ 3. Ways to Handle Events in JavaScript

There are three main ways to attach event handlers:


βœ… Method 1: HTML Event Attributes (Inline)

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

<script>
  function greet() {
    alert("Hello from inline event!");
  }
</script>

πŸ”Ή Simple but not recommended for larger projects. Keeps logic mixed with HTML.


βœ… Method 2: Using DOM Element Properties

<button id="btn">Click</button>

<script>
  let button = document.getElementById("btn");
  button.onclick = function () {
    alert("Button clicked!");
  };
</script>

πŸ”Ή Better than inline, but still only allows one handler per event.


βœ… Method 3: Using addEventListener()

<button id="btn">Click</button>

<script>
  let button = document.getElementById("btn");

  button.addEventListener("click", function () {
    alert("Handled using addEventListener!");
  });
</script>

πŸ”Ή This is the recommended way:

  • Keeps JavaScript and HTML separate

  • Allows multiple listeners

  • Works with all event types


πŸ“Œ 4. Common Event Types

Event TypeDescription
clickWhen user clicks an element
mouseoverMouse hovers over an element
mouseoutMouse leaves an element
keydownThe key is pressed down
keyupKey is released
inputUser types in input field
submitThe form is submitted
changeThe value of an input changes
loadPage or image finishes loading

πŸ“Œ 5. Event Object

Every event returns an event object that contains useful information such as

element.addEventListener("click", function (event) {
  console.log(event.type);       // "click"
  console.log(event.target);     // element that was clicked
});

βœ… The eventobjectis automatically passed to the event handler.


πŸ“Œ 6. Handling Input Events

πŸ”Ήβ£input Event (fires as the user types)

<input id="name" type="text">

<script>
  document.getElementById("name").addEventListener("input", function (e) {
    console.log("Typed: " + e.target.value);
  });
</script>

πŸ“Œ 7. Handling Form Submit Event

Prevent the form from refreshing the page using event.preventDefault().

<form id="myForm">
  <input type="text" />
  <button type="submit">Submit</button>
</form>

<script>
  document.getElementById("myForm").addEventListener("submit", function (e) {
    e.preventDefault(); // stops page reload
    alert("Form submitted!");
  });
</script>

πŸ“Œ 8. Removing Event Listeners

You can remove an event listener uusingremoveEventListener()

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

let btn = document.getElementById("btn");
btn.addEventListener("click", sayHello);

// To remove it:
btn.removeEventListener("click", sayHello);

🚫 Note: You must pass the same function reference when removing.


πŸ“Œ 9. Event Delegation (Advanced Concept)

Instead of attaching events to multiple child elements, you can attach a single event listener to a parent and use iitevent.targetto identify what was clicked.

<ul id="myList">
  <li>Item 1</li>
  <li>Item 2</li>
</ul>

<script>
  document.getElementById("myList").addEventListener("click", function (e) {
    if (e.target.tagName === "LI") {
      alert("Clicked on: " + e.target.textContent);
    }
  });
</script>

βœ… Useful for dynamic elements created later with JavaScript.


πŸ“Œ 10. Summary Table

TaskMethod Example
Attach event (best method)addEventListener("click", function)
Access event infofunction(e) { e.target, e.type }
Prevent form reloadevent.preventDefault()
Detect input typingaddEventListener("input", function)
Detect form submissionaddEventListener("submit", function)
Remove eventremoveEventListener("click", handlerFunction)

πŸ“˜ Mini Practice Project: Toggle Text

<button id="toggleBtn">Show/Hide</button>
<p id="text" style="display: none;">Hello JavaScript Events!</p>

<script>
  let button = document.getElementById("toggleBtn");
  let text = document.getElementById("text");

  button.addEventListener("click", function () {
    if (text.style.display === "none") {
      text.style.display = "block";
    } else {
      text.style.display = "none";
    }
  });
</script>

βœ… Final Tips

  • Use addEventListener() for all modern JS event handling.

  • Always pass a named function when you need to remove it later.

  • Use event.target to identify the exact element interacted with.

  • For forms, always use preventDefault() to avoid refresh.