Skip to content

Instantly share code, notes, and snippets.

@cbejensen
Last active October 8, 2022 06:36
Show Gist options
  • Save cbejensen/bf9d14c26fd81abb97cd48862a71b903 to your computer and use it in GitHub Desktop.
Save cbejensen/bf9d14c26fd81abb97cd48862a71b903 to your computer and use it in GitHub Desktop.
Track Clicks with Gtag
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Track Clicks</title>
</head>
<body>
<button class="btn-to-track">Click Me!</button>
<a class="link-to-track" href="/cool-stuff">Fake link to cool stuff</a>
<script src="./index.js"></script>
</body>
</html>
const btn = document.querySelector('.btn-to-track')
const link = document.querySelector('.link-to-track')
trackClicks(btn, 'button', 'header-button-awesome')
trackClicks(link, 'link', 'link-to-cool-stuff')
function trackClicks(elem, category, label) {
elem.addEventListener('click', reportToGtag)
function reportToGtag(e) {
e.preventDefault()
if (window.gtag) { // if we have access to gtag
gtag('event', 'click', {
event_category: category,
event_label: label
})
console.log('reported:', label)
} else {
console.warn('gtag has not been initiated - click not reported')
}
elem.removeEventListener('click', reportToGtag) // only report first click
if (e.ctrlKey && elem.href) { // if ctrl key was held, open link in new tab
window.open(elem.href)
} else {
elem.click()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment