JS to add click events for offsite links
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

I need to be able to add click events for GA to links that are going to a different domain. This way we can track how much traffic we are sending. Ideally we can specify a specific Div that the js will parse so we dont mess with links not in our specific body/article area of content.

so ideally you have something like this

<a href="https://www.offsitedomain.com/franchising/">outbound link</a>

and your code will add this onclick event to it

<a href="https://www.bigblueswimschool.com/franchising/" onClick="ga('send', 'event', 'Outbound Domain', 'click', 1);">outbound link</a>

ideally if you find anything else in the anchor you will persist it and just add the onclick event.

code should have no dependency on jquery, and work in major common browsers.

"if you find anything else in the anchor you will persist it and just add the onclick event" Does this mean you want to add the onclick event to all elements in the anchor? Or just the links?
BrianSantoso 2 months ago
@Qdev let me know if I should improve or redo my solution
SirYummy 2 months ago
awarded to Wuddrum
Tags
javascript

Crowdsource coding tasks.

3 Solutions

Winning solution

Hey, here's my trivial solution:

Demo/Source: JsFiddle

Usage

Include the script and initialize a new gaOnClickAttach instance with an array of your selectors. And then call attach() method on created instance. E.g.:

<script src="ga-onclick-attach.js"></script>
<script>
    var gaAttacher = new gaOnClickAttach([
        'body > a',
        '#moreLinks'
    ]);
    gaAttacher.attach();
</script>

Works on all modern browsers & IE8+.

Edit1-3: Fixed formatting issues.

Edit4: Added check for local links.


Instructions

  • Paste the following code wherever you want it to run and change the div id to the one you are targeting.

Working example

Edit JS to add click events for offsite links

(() => {
  let ga = ga||(() => console.log('Outbound link clicked')) // optional 

  const addGaOnclickToExternalLink = (link) => {
    const url = link.getAttribute('href')
    const host = window.location.hostname.toLowerCase()
    const regex = new RegExp('^(?:(?:f|ht)tp(?:s)?\:)?//(?:[^\@]+\@)?([^:/]+)', 'im')
    const match = url.match(regex)
    const domain = (
      (
        match 
        ? match[1].toString() 
        : (
            (url.indexOf(':') < 0) 
            ? host 
            : ''
        )
      )
    )
    .toLowerCase()

    // Same domain
    if (domain !== host) {
      link.addEventListener('click', event => {
        ga('send', 'event', 'Outbound Domain', 'click', 1)
        // or:  ga('send', 'event', domain, 'click', 1)
      })
    }
  }

  const targetContainer = document.getElementById('replace-with-your-div-id') // TODO: change me!
  const links = targetContainer.querySelectorAll('a')
  links.forEach(link => {
    addGaOnclickToExternalLink(link)
  })
})()

Pure JavaScript

Works on all browsers, all versions. No need for any external dependencies, so code is easily manageable and is guaranteed to work across all versions of JS. Also no need to worry about DOM elements loading in the wrong order or pesky event listeners stifling your website's performance.

Just paste anywhere into your javascript and you're good to go :)

window.onload = function(){

    const div_to_parse = "your-divs-id" // id of the div to parse

    const div = document.getElementById(div_to_parse)
    let links = div.querySelectorAll("a")
    links = Array.prototype.filter.call(links, isOutbound)
    links.forEach(link => {
        link.onclick = function(){
            ga('send', 'event', 'Outbound Domain', 'click', 1);
        }
    })
}

function isOutbound(link){
    const url = link.getAttribute('href')
    const host = window.location.hostname.toLowerCase()
    const regex = new RegExp('^(?:(?:f|ht)tp(?:s)?\:)?//(?:[^\@]+\@)?([^:/]+)', 'im')
    const match = url.match(regex)
    const domain = ((match ? match[1].toString():((url.indexOf(':') < 0) ? host : ''))).toLowerCase()

    return domain != host
}

Usage

Just change the "your-divs-id" to the id of the div you want to parse.

There is a safeguard so that links directing you to your own website (in-site link) will not trigger the event

Demo

https://briansantoso.github.io/outbound-links/

Sample HTML

https://github.com/BrianSantoso/outbound-links/blob/master/index.html

View Timeline