DOM Events Basics in JavaScript

Learn DOM events in JavaScript with addEventListener, named and arrow handlers, removeEventListener and the event object. Simple explanation and output.

BeginnerJavaScript Events ProgramsExample 1 of 10

This code needs a web page. Add the HTML elements it looks up by id, link the script, and open the page in a browser. Node has no document object. Here you need <button id="myButton">Click</button>.

dom-events-basics.js
1// Method 1: Inline event handler (not recommended)
2// <button onclick="handleClick()">Click</button>
3
4// Method 2: addEventListener (recommended)
5const button = document.getElementById('myButton');
6
7button.addEventListener('click', function(event) {
8 console.log('Button clicked!');
9 console.log('Event:', event);
10 console.log('Target:', event.target);
11});
12
13// Method 3: Named function
14function handleClick(event) {
15 console.log('Clicked!', event.target);
16}
17
18button.addEventListener('click', handleClick);
19
20// Method 4: Arrow function
21button.addEventListener('click', (e) => {
22 console.log('Arrow function handler');
23});
24
25// Method 5: Multiple events
26button.addEventListener('click', handleClick);
27button.addEventListener('mouseenter', function() {
28 console.log('Mouse entered');
29});
30button.addEventListener('mouseleave', function() {
31 console.log('Mouse left');
32});
33
34// Method 6: Remove event listener
35button.removeEventListener('click', handleClick);
36
37// Method 7: Event object properties
38button.addEventListener('click', function(e) {
39 console.log('Type:', e.type);
40 console.log('Target:', e.target);
41 console.log('Current Target:', e.currentTarget);
42 console.log('Timestamp:', e.timeStamp);
43 console.log('Bubbles:', e.bubbles);
44 console.log('Cancelable:', e.cancelable);
45});

Sample Output

Arrow function handler

Listeners run in the order they were added. handleClick does not print because it was removed.

Timestamp: 2215.4

Milliseconds since the page started loading. Your number will differ.

In this one

  • What a DOM event and an event listener are
  • Why addEventListener beats inline onclick
  • How to remove a listener with the same function
  • What target, currentTarget, type and preventDefault do

How it works

  1. 1

    The button is found with getElementById.

  2. 2

    An anonymous click listener logs the event and its target.

  3. 3

    handleClick is added, then added again (the browser ignores the duplicate).

  4. 4

    Hover listeners log Mouse entered and Mouse left.

  5. 5

    removeEventListener removes handleClick.

  6. 6

    A final listener prints the event object properties.

Edge cases

Element not found

getElementById returns null and addEventListener throws a TypeError.

Run the script after the HTML loads, for example with defer or at the end of body.

Removing an anonymous function

removeEventListener with a new function does nothing.

Store the handler in a named function or variable and pass the same reference.

Calling the handler by mistake

addEventListener('click', handleClick()) runs it at once.

Pass handleClick without brackets.

What's going on

A DOM event is a signal the browser sends when something happens on the page. The DOM is the browser's model of your HTML. Events let your code react when a student clicks a "Submit attendance" button, moves the mouse, or presses a key.

The program starts with the old way: an inline handler such as onclick="handleClick()" written inside the HTML. It still works, but it is not recommended. It mixes HTML with JavaScript and allows only one handler per event.

The modern way is addEventListener. An event listener is a function the browser calls when the event happens. You can add many listeners for the same event, and you can remove them later. That is why it is the preferred method and more flexible.

You can pass an anonymous function, a named function like handleClick, or an arrow function. A named function matters when you want to remove it. removeEventListener needs the exact same function reference, so you cannot remove an anonymous function.

Common event types are click for a mouse click, mouseenter and mouseleave for hover, keydown and keyup for keyboard, submit for forms, load when the page has loaded, and scroll when the page scrolls.

Every handler receives an event object. type is the event name. target is the element that triggered the event. currentTarget is the element the handler is attached to. preventDefault() stops the browser's default action, such as following a link. stopPropagation() stops the event from bubbling up to parent elements.

Good habits: use addEventListener, remove listeners when you are done, and use event delegation for content added later.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Which method is recommended for handling events?

Pick an answer to check it.

Question 2

What does preventDefault() do?

Pick an answer to check it.

Questions people ask

Why did handleClick not print Clicked!?

It was removed in Method 6, and adding the same function twice only registers it once.

What is the difference between target and currentTarget?

target is what was actually clicked. currentTarget is the element that owns the listener.

Can one element have many click listeners?

Yes. They run in the order they were added.