All files / public navigation-events.ts

100% Statements 25/25
92.85% Branches 13/14
100% Functions 6/6
100% Lines 25/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 673x   3x     3x   3x     6x 6x 2x 3x 3x                         3x     3x 3x 1x     5x 1x   4x 1x   3x 1x   2x 1x     1x   5x 5x 5x                            
const currentOrigin = window.location.href;
// @ts-expect-error: dataLayer is defined in the global scope
const { dataLayer } = window;
 
// Main navigation
addGANavEvents("#navigation", "charmhub.io-nav-1");
// Footer events
addGANavEvents("footer", "charmhub.io-nav-footer");
 
function addGANavEvents(target: string, category: string) {
  const t = document.querySelector(target);
  if (t) {
    Array.from(t.querySelectorAll<HTMLAnchorElement>("a")).forEach((a) => {
      a.addEventListener("click", () => {
        dataLayer.push({
          event: "GAEvent",
          eventCategory: category,
          eventAction: "from:" + currentOrigin + " to:" + a.href,
          eventLabel: a.text.trim(),
          eventValue: undefined,
        });
      });
    });
  }
}
 
// Content events
addGAContentEvents("#main-content");
 
function addGAContentEvents(target: string) {
  const t = document.querySelector(target);
  if (t) {
    Array.from(t.querySelectorAll<HTMLAnchorElement>("a")).forEach((a) => {
      let category: string;
      // Primary CTA
      if (a.classList.contains("p-button--positive")) {
        category = "charmhub.io-content-cta-0";
        // Secondary CTA
      } else if (a.classList.contains("p-button")) {
        category = "charmhub.io-content-cta-1";
        // Listing navigation
      } else if (a.classList.contains("p-tabs__link")) {
        category = "charmhub.io-nav-listing";
        // Content cards
      } else if (a.classList.contains("p-card--button")) {
        category = "charmhub.io-content-card";
      } else {
        // Other text links
        category = "charmhub.io-content-link";
      }
      Eif (!a.href.startsWith("#")) {
        a.addEventListener("click", () => {
          dataLayer.push({
            event: "GAEvent",
            eventCategory: category,
            eventAction: "from:" + currentOrigin + " to:" + a.href,
            eventLabel: a.text.trim().split("\n")[0],
            eventValue: undefined,
          });
        });
      }
    });
  }
}
 
export {};