JSFiddle - React, Tailwind, and code Playground

by Andrew Holloway

HTML

<html>
<body id='app'>
  <button data-test-1='a' data-test-2="b">
  test
  </button>
  <div>
    <a name="test" id='1' href="http://example.com/">test link</a>
  </div>
</body>
</html>

JavaScript

const trackableEvents = ['click'];
const clickableElements = ['a', 'button'];
const requiredAttrs = ['id', 'name'];

// Set up on Capture phase so it can trigger before links are navigated to, etc.
trackableEvents.forEach(eventName => {
  document.addEventListener(eventName, function(ev) {
    if (clickableElements.includes(ev.target.tagName.toLowerCase())) {
      console.log('call tracking on', ev.target.tagName, 'with id', ev.target.id, 'and dataset', ev.target.dataset, ev.target.attributes)
    }

    // Handle any missing component attributes
    const attrs = ev.target.attributes;
    requiredAttrs.forEach(function(requiredAttr) {
      for (const attr of attrs) {
        if (attr.name === requiredAttr) return;
      }
      console.warn('all interactive elements must specify at least', requiredAttr, ': missing in', ev.target);
    });
  }, true);
})