VCF

Unit 6 · JavaScript in the page

'click' vs onclick: naming events in JavaScript

With addEventListener, write the bare event name: 'click', 'input', 'submit'. The on prefix belongs to properties like button.onclick. addEventListener('onclick', …) listens for an event that never happens.

The mix-up

What people often think

“The event is called onclick.”

What the tutor says

With addEventListener the event name is just 'click'. The on- prefix belongs to the onclick property.

How it works

Each element has the events that fit it. Typing in a box fires input, sending a form fires submit, and pressing a button fires click.

Read the handler’s name as well as the event. The connection decides what happens, so check that the function makes sense for that element.

Side by side

The mix-upJavaScript
button.addEventListener('onclick', addToCart);
No event is called onclick.
What worksJavaScript
button.addEventListener('click', addToCart);
search.addEventListener('input', filterList);
Bare event names.

Close cousins of this mix-up

The tutor watches for these in the same lesson.

  • “Every element listens for click.”

    Each element has the event that fits it. Typing in a box fires input, and sending a form fires submit.

  • “Any function will do, as long as something is connected.”

    The cable decides what happens. Read the function name and ask whether it fits that element.

Practise it with a tutor watching

Events

Connect a click, a keystroke or a form to the function that should run.

15 minutes See it Build it Break it Say it
Start the lesson

Free, no account needed.