CodeBlanks Logo Icon CodeBlanks

The event object

JavaScript course · Intermediate · Lesson 35/134

Learn to use the event object's target and type properties.

The event object

When an event listener fires, an event object is passed to the function. This object carries everything about the event: type, target element, key value, mouse position and more.

button.addEventListener('click', (event) => {
  console.log(event.type);
  console.log(event.target);
});

You can name the handler parameter anything; common choices are event or short e. If you do not declare the parameter, you cannot access the event object; but the event still fires.

target vs currentTarget

event.target gives the actual element where the event started; for example if you click an icon inside a button, the icon is the target. event.currentTarget gives the element the listener is attached to; so always the same button.

list.addEventListener('click', (event) => {
  console.log(event.target);
  console.log(event.currentTarget);
});

target can change, currentTarget stays the same. This difference matters for event propagation, which we cover in the next group.

Exercise Log event.target and event.type

Select the btn element with document.querySelector('.btn'). Add a handler with addEventListener('click', ...); the handler parameter should be event and it should call console.log(event.target) and console.log(event.type) inside.

Show example solution
const button = document.querySelector('.btn');
button.addEventListener('click', (event) => {
  console.log(event.target);
  console.log(event.type);
});

Test yourself

  1. Which gives the actual element where the event started?

    • event.type
    • event.currentTarget
    • event.target
    • event.key
    Show answer

    event.target — Correct! event.target gives the actual element that was clicked.

  2. Add the handler parameter

    button.addEventListener('click', (____) => {
      console.log(event.target);
    });
    Show answer
    button.addEventListener('click', (event) => {
      console.log(event.target);
    });
  3. Match the event properties

    event.target
    Actual clicked element
    event.type
    Event name
    event.currentTarget
    Attached element
    event.key
    Pressed key

All lessons in Intermediate