Last active
May 13, 2020 12:57
-
-
Save simonexmachina/c534e193dc5824b5965e365efc9e8df2 to your computer and use it in GitHub Desktop.
Improving Elements Analytics - Proof of Concept
This file contains hidden or 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
// Run addDataLayerTracking for each form to be tracked | |
// When the user enters invalid information call trackValidationError | |
export function addFormTracking(form) { | |
form.addEventListener('change', ev => { | |
let option = null | |
if (input.type == 'checkbox') { | |
option = input.checked ? 'Checked' : null | |
} | |
else if (input.type == 'radio') { | |
option = input.dataset.trackingLabel | |
} | |
// we might to set and unset in the calls to dataLayer.push | |
dataLayer.push({ | |
event: 'formChange', | |
formId: form.dataset.trackingId, | |
inputId: input.dataset.trackingId, | |
option, | |
}) | |
}) | |
form.addEventListener('submit', ev => { | |
dataLayer.push({ | |
event: 'formSubmit', | |
formId: form.dataset.trackingId, | |
}) | |
}) | |
} | |
export function trackValidationError(form, input, message) { | |
dataLayer.push({ | |
event: 'formInvalid', | |
formId: form.dataset.trackingId, | |
inputId: input.dataset.trackingId, | |
message, | |
}) | |
} |
This file contains hidden or 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
// Run addLinkTracking on the document (on load) | |
export function addLinkTracking(document) { | |
document.body.addEventListener('click', ev => { | |
// only track clicks on a or button that have a tracking ID | |
const element = ev.target.closest('a[data-tracking-id], button[data-tracking-id]') | |
if (!element) { | |
return | |
} | |
const block = getBlock(element) || document.createElement('div') | |
dataLayer.push({ | |
event: 'click', | |
pageId: body.dataset.trackingId, | |
blockId: block.dataset.trackingId, | |
blockLabel: block.dataset.trackingLabel, | |
elementId: element.dataset.trackingId, | |
elementLabel: element.dataset.trackingLabel, | |
tagName: element.tagName, | |
blockPosition: getPosition(block), | |
elementPosition: getPosition(element), | |
}) | |
} | |
} | |
function getBlock(element) { | |
return element.parentNode.closest('[data-tracking-id]') | |
} | |
function getPosition(element) { | |
const parent = element.parentNode | |
if (['ul', 'ol'].includes(parent.tagName)) { | |
return Array.from(parent.children).indexOf(element) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment