Skip to main content
Support home / Event conversions

Track external link clicks

Events as external clicks

If you want to track a few key external links that people could click on from your site to somewhere on the internet, you could do something like this:

<a href="https://amazon.com/x" class="sponsored">Link to Amazon</a>
<a href="https://bestbuy.com/x" class="sponsored">Link to Bestbuy</a>

Where you'd add sponsored as a class to each link you wanted to collect data for. And then you'd add the following javascript to generate the events:

<script>
window.addEventListener('load', (event) => {
document.querySelectorAll('.sponsored').forEach(item => {
item.addEventListener('click', event => {
let url = new URL(item.getAttribute('href'));
let domainParts = url.hostname.split('.');
let domainName = domainParts.length > 1 ? domainParts[domainParts.length - 2] : domainParts[0];
 
fathom.trackEvent(`Sponsor clicked: ${domainName}`);
});
});
});
</script>

For another example, if you wanted to track ALL external link clicks, you could use the following javascript:

<script>
window.addEventListener('load', (event) => {
document.querySelectorAll('a').forEach(item => {
item.addEventListener('click', event => {
let linkUrl = new URL(item.getAttribute('href'), window.location.href); // Using the second argument to handle relative URLs
let currentHostname = window.location.hostname;
 
if (linkUrl.hostname !== currentHostname) { // If the link's hostname is different from the current page's hostname
let domainParts = linkUrl.hostname.split('.');
let domainName = domainParts.length > 1 ? domainParts[domainParts.length - 2] : domainParts[0];
 
fathom.trackEvent(`External link clicked: ${domainName}`);
}
});
});
});
</script>


If you still have questions or require help with anything, please reach out to us and we'll happily get things sorted out for you.


Can't find what you're looking for?