Last active
August 13, 2024 11:24
-
-
Save Kugelschieber/854c0df62fc476686d3f9a504e811d33 to your computer and use it in GitHub Desktop.
Pirsch Custom Event Form Submission
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
function findFormTitle(node) { | |
const tag = node.tagName; | |
if (tag === "H1" || tag === "H2" || tag === "H3" || tag === "H4") { | |
return node.innerText; | |
} | |
for (const child of node.children) { | |
const title = findFormTitle(child); | |
if (title) { | |
return title; | |
} | |
} | |
return null; | |
} | |
function trackForms() { | |
document.querySelectorAll("form").forEach(form => { | |
let eventName = findFormTitle(form); | |
if (!eventName) { | |
if (form.hasAttribute("id")) { | |
eventName = form.getAttribute("id"); | |
} else { | |
eventName = "Form Submission"; | |
} | |
} | |
console.log("Found form: ", eventName); | |
let preventSubmission = true; | |
form.addEventListener("submit", e => { | |
if (preventSubmission) { | |
e.preventDefault(); | |
preventSubmission = false; | |
} | |
const fields = form.querySelectorAll("input"); | |
const meta = {}; | |
fields.forEach(i => { | |
const t = i.getAttribute("type").toLowerCase(); | |
if (t !== "hidden" && t !== "submit") { | |
meta[i.getAttribute("name")] = i.value; | |
} | |
}); | |
pirsch(eventName, { meta }).finally(() => e.target.submit()); | |
}); | |
}); | |
} | |
function trackButtons() { | |
document.querySelectorAll(".elementor-button-link").forEach(button => { | |
button.addEventListener("click", () => { | |
pirsch("Button Click", { | |
meta: { | |
link: button.getAttribute("href") ?? "not set" | |
} | |
}); | |
}); | |
}); | |
} | |
document.addEventListener("DOMContentLoaded", () => { | |
trackForms(); | |
trackButtons(); | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment