javascript

Plain JS Notes

Setting a click on the document, to capture clicks on all elements:

document.addEventListener("click", myFunction);

function myFunction(e) {
  console.log('arg:', e);
  console.log('arg:', e.attributes);
  console.log('arg:', e.classList);
  console.log('arg:', e.dataset);
  console.log('arg:', e.target); // Just prints the html, even though e.target has stuff in it
  console.log('arg:', e.target.nodeName); // A, H1, P, etc
}


A click tracker that bubbles up to find an item with a certain attribute:

      document.addEventListener('DOMContentLoaded', function() {
        let checkForTrackingClick = function (event, bubbleUpNode) {
          let node = bubbleUpNode ? bubbleUpNode : event.target;
          let parent = node.parentNode;

          if (!parent)
            return;

          // Only handle Clicks on A-tags with a data attribute set:
          if (node.nodeName != 'A' || !node.dataset['aCertainDataAttribute'])
            return checkForTrackingClick(event, parent);

          let id   = node.dataset['aCertainDataAttribute'];
          let type = node.dataset['aCertainDataAttribute2'];

          someTrackingFunction(id, type);
        }

        document.addEventListener("click", checkForTrackingClick);
      });