Skip to content

Instantly share code, notes, and snippets.

@g4rcez
Created November 5, 2021 14:50
Show Gist options
  • Save g4rcez/ad7950bfc14a6bb439d473146d24ec6d to your computer and use it in GitHub Desktop.
Save g4rcez/ad7950bfc14a6bb439d473146d24ec6d to your computer and use it in GitHub Desktop.
export const initObserver = (root: HTMLElement) => {
const dataset = {
ga: "data-ga",
inspect: "data-inspect",
};
const observer = new MutationObserver((params) => {
params.forEach((node) => {
if (!(node.target as any).querySelectorAll) return [];
const htmlElement: HTMLElement = node.target as any;
const buttonsWithGaFlag: HTMLButtonElement[] = Array.from(
htmlElement.querySelectorAll(
`button[${dataset.ga}]:not(${dataset.inspect})`
)
);
buttonsWithGaFlag.forEach((button) => {
const gaMetric = button.dataset.ga!;
const hasInspect = button.dataset.inspect!;
if (hasInspect) {
return;
}
button.addEventListener("click", () => {
console.log(`Push ${gaMetric} to GA`);
});
button.setAttribute(dataset.inspect, "true");
});
});
});
observer.observe(root, {
attributes: true,
childList: true,
subtree: true,
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment