JavaScript Manipulating Document Events

Add event listeners

We can add event listeners to any node where we wait for some specific type of event to occur and then call a function. For example we can wait for someone to click a button before we fetch data from an API.

The addEventListener method takes two mandatory parameters: the type of the event we want to listen for and the function that should be called when an even of that type happens.

Read more on MDN

EventTarget.addEventListener()

Event types

There are more than a hundred types of events we can listen for. The ones we are going to use most often are:

  • click: Trigger by a pointing device button being pressed and released.
  • drag: Triggered by an element or text selection being dragged.
  • keyup: Triggered when any key is released.

Read more on MDN

Event reference

Code example

<p>
Count: <span id="count">0</span>
<button id="plusOneButton">+1</button>
</p>
<script>
// state
let count = 0
const btn = document.querySelector("#plusOneButton")
const counter = document.querySelector("#count")
btn.addEventListener("click", () => {
count += 1
counter.innerText = count
})
</script>

In the example above, we add a click event listener to a button and increase the number (inner text) of another node every time we click the button.

Code and Preview

Description

The example below uses a combination of event listeners, external data fetching and modification of the DOM to create a simple Wikipedia search app.

Error handling has intentionally been left out to keep the example short. How would you go about adding error handling here?

Editor
Preview