CJCoding With Joseph
15free / daySign inCreate account

JavaScript For Web

Using addEventListener

In the last lesson, we used the onclick attribute to run a function when a button was clicked. That works fine for small pages, but it mixes your HTML and JavaScript together, which can make your code messy and harder to manage.

A better way is to keep all your JavaScript separate and attach actions from your script file. To do that, we use a built-in method called addEventListener().


What addEventListener Does

This method lets JavaScript listen for an action on an element, like a click, hover, or key press, and then run a function when it happens.

element.addEventListener("eventType", functionToRun);
  • The first part "eventType" tells the browser what you are listening for, such as "click" or "mouseover".

  • The second part is the function that will run when that event happens.

Members only

Keep reading this lesson

You've reached the end of the free preview. Unlock the rest of this lesson plus 10 more lessons in JavaScript For Web.

  • Unlimited coding questions
  • Unlimited access to all classroom material
  • Weekly live call for questions and guidance
  • 3,000 AI tutor tokens / month
  • Personal SQL database (3 MB)
  • Progress tracking

Cancel any time.