Don't have one? Create one ↗
JavaScript for GTM

Lesson 6 of 8

Writing Event Listeners

When an interaction has no dataLayer push and no built-in trigger, you write a listener: a small Custom HTML tag that watches for something and pushes your own event.

<script>
  (function () {
    // Fire when a user copies text from a pricing table
    var table = document.querySelector('#pricing');
    if (!table) return;
    table.addEventListener('copy', function () {
      window.dataLayer.push({ event: 'pricing_copied' });
    });
  })();
</script>

The patterns you will reuse

  • Event delegation: listen on a parent, check e.target.matches(...), so it works for elements added later.
  • Guard first: bail out (if (!el) return;) when the element isn't there, so you never throw.
  • Listen to APIs: many embeds expose their own events (player.on('play')), subscribe and push.

Key takeaway

A listener is "watch for X, push an event". Use delegation for robustness and always guard against missing elements so a listener never breaks the page.