Events in JS

Finally, and probably the most important thing we'll touch on is events.

What if when a post is clicked, we want to ask the user if they're interested in editing this post?

For this, we need to set up an event. We can do this in JavaScript, but listening to an event on a given element.

For this, we select an element. In this case, our post, and we use the addEventListener. This takes two arguments, a string event that we want to listen for, in this case, the click event, and then a callback function which determines what should happen when the event takes place.

const post = document.querySelector(".post");
post.addEventListener("click", (event) => {
  console.log(event);
});

And in the parameters of the callback, we get access to data about the event from this event object, which we can log.

The most important information is usually on event.target, which for many events tells us the target or the element that was clicked (if a click event) or hovered (if using a mouse over event, etc)

const post = document.querySelector(".post");
post.addEventListener("click", (event) => {
  console.log(event.target);
});

But here, what's important is to console.log and ask the user--do you want to edit this post?

const post = document.querySelector(".post");
post.addEventListener("click", (event) => {
  // console.log(event.target);
  console.log("Do you want to edit this post?");
});

And we see that this works for the first post. But how do we register click events for all of our posts? We need to use querySelectorAll, iterate over the NodeList with forEach and then for each one, set up an event listener:

const posts = document.querySelectorAll(".post");
posts.forEach((post) => {
  post.addEventListener("click", (event) => {
    // console.log(event.target);
    console.log("Do you want to edit this post?");
  });
});

But be aware of the fact that querySelectorAll will only give us a static list. If changes are made to the DOM, it's not going to set up event listeners on those new elements.

So the fix to this if new elements are added is to put an event listener on the document body and check the event target to see if it matches the given element we want to apply the listener to. If so, perform the action:

document.body.addEventListener("click", (event) => {
  // if (!event.target.matches(".post")) return;

  console.log("Do you want to edit this post?");
});

Note that there are a ton of valuable events after click. We unfortunately don't have time to cover them all, but a few useful ones are mouseover and mouseout. Mouseover works when a user moves their mouse over an element, mouseout when they do the opposite, move out of an element.

And we can listen to keyboard events with keydown and keyup. They names describe exactly what they do--keydown for the down part of a key press. key up for when the key is released.