

To activate event delegation, you’ll need to set the last parameter in the document.addEventListener() call to true instead of false. Note, this doesn’t bubble by default, meaning a listener on the document node won’t be able to catch it. the user enters a form field, types something in, and leaves the field).Ĭlick - A click is registered on an element (use GTM’s Click Listener instead).Ĭontextmenu - The right mouse button is clicked.ĭblclick - A double-click is registered on an element.įocus - An element has received focus (e.g. To activate event delegation, you’ll need to set the last parameter in the document.addEventListener() call to true instead of false.Ĭhange - The value of an element changes between receiving and losing focus (e.g. when someone is closing the browser window).īlur - An element has lost focus (e.g. Here’s MDN’s excellent guide on creating and triggering events.Īnyway, here’s a list of some of the most popular event types:īeforeunload - Fire a listener when the window, the document, and all resources are about to be unloaded (e.g. Remember, you can also dispatch and listen to your own custom events, which makes this solution even more flexible. For the full list of supported types, follow this link. On the first line, you specify just what type of event you want to listen for. Join over 13k others.( UPDATE Due to a change in how macros work in Debug Mode, the ) Hate the complexity of modern front‑end web development? I send out a short email each weekday on how to build a simpler, more resilient web. 🔥 Hot off the press! Explore new guides on Testing Vanilla JS and working with the command line, part of a new Tooling Bundle. It’s more performant to have a single event listener that listens for all clicks and check if the element has a selector you want than it is to attach a bunch of individual listeners. I think the danger of accidentally doing so is too great, and as a best practice, would recommend avoiding setting event listeners this way.

So we’re cool as long as we don’t use i in the event listener? When you try to log btns in the event listener, it’s try to reference an index that doesn’t exist in the node list. When our i < btns.length check runs, it fails because i is bigger than the number of items in our node list, and the loop ends. It changes.Īfter the last iteration of the loop, i is increased by 1 one last time. The value does not remain constant within the scope of your event listener callback function. Why is that? The i variable isn’t scoped to the loopĪfter each iteration of the loop, the i variable increases by 1. You can see in the demo that the buttons initially log fine, and event.target works, but btns logs undefined. querySelectorAll ( 'button' ) for ( var i = 0 i < btns.
