#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
JavaScript Fundamentals

Event handler

An event handler is a function that runs when a specific event happens on a page, such as a click, a key press, a form submission or the mouse moving over an element. Handlers are how a static page becomes interactive: the browser detects the event and calls the function you attached to it.

Three ways to attach a handler

JavaScript has grown several ways to connect a function to an event:

  1. Inline HTML attributes, such as <button onclick="save()">. This mixes behaviour into markup and is hard to maintain.
  2. DOM properties, such as button.onclick = save. Simple, but an element can hold only one handler per event this way; assigning again replaces the first.
  3. addEventListener, such as button.addEventListener('click', save). This is the recommended approach. It allows several handlers for the same event, supports options, and can be removed cleanly.

Using addEventListener and the event object

When the browser calls your handler, it passes an event object describing what happened. It includes event.type, event.target (the element where the event started), mouse coordinates, the key pressed, and methods like preventDefault().

<button id="like">Like</button>
<span id="count">0</span>
<input id="search" placeholder="Press Enter to search">

<script>
  const likeBtn = document.getElementById('like');
  const countEl = document.getElementById('count');
  let likes = 0;

  function handleLike(event) {
    likes += 1;
    countEl.textContent = likes;
    console.log('Clicked:', event.target.id);
  }

  likeBtn.addEventListener('click', handleLike);

  document.getElementById('search').addEventListener('keydown', (e) => {
    if (e.key === 'Enter') {
      console.log('Searching for', e.target.value);
    }
  });
</script>

Notice that handleLike is passed without brackets. The browser needs the function itself so it can call it later.

Preventing default behaviour

Some events come with built-in browser actions: clicking a link navigates, submitting a form reloads the page, pressing a key types a character. Calling event.preventDefault() inside the handler cancels that default action, which is how you handle form submission with JavaScript instead of a full page reload.

The mistake of calling the function too early

A very common bug looks like this: likeBtn.addEventListener('click', handleLike()). The brackets run handleLike immediately when the line executes, and its return value (undefined) is registered as the handler. Nothing happens on click. If you need to pass extra arguments, wrap the call in an arrow function: addEventListener('click', () => handleLike(5)).

A second common bug is trying to attach a handler before the element exists. If your script runs in the <head>, getElementById returns null and the call throws. Place scripts at the end of <body> or use the defer attribute.

Removing handlers and useful options

removeEventListener must receive the exact same function reference that was added. An anonymous arrow function cannot be removed later, because you have no reference to it, so give handlers a name when you plan to remove them.

The third argument of addEventListener accepts options:

  • { once: true } removes the handler automatically after it runs once.
  • { passive: true } promises you will not call preventDefault, which helps scrolling performance for touch and wheel events.
  • { capture: true } runs the handler during the capture phase, which the next lesson on event flow explains.

Rule to take away: use addEventListener, pass the function without calling it, read details from the event object, and keep a named reference if you will need to remove it.

Ready to master real-world web development?

Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.

Explore Course