How to track outbound clicks using Javascript

I am trying to use the code given here: Make a ping to a URL without redirecting . OP asked for ping url without opening multiple windows. I would like to do this, but I want to actually visit the second url to track outbound clicks in my server analytics.

Here is the code I'm trying to do:

<a href="javascript:;" onclick="visitPageX()">link</a>

function visitPageX() {
  // send Ajax request to the track URL
  setTimeout(function() {
    location.href = 'http://{pageXURL}';
  }, 300);
}

      

However, I do not understand where I should be putting my "Tracking URL". Here's my attempt:

<a href="javascript:;" onclick="visitPageX()"><a href="http://externalsite.com/">anchor text</a></a>

function visitPageX() {
  // send Ajax request to the track URL
  setTimeout(function() {
    location.href = 'http://externalsite.com/';
  }, 300);
}

      

I'm stuck with where to put

http://examplemysite.com/tracking.php?123

      

so I can count outgoing clicks. I would appreciate if you could help me get this code to work or provide an even better outbound click tracking solution without using Google Analytics.

Your support is greatly appreciated.

0


source to share


1 answer


This example uses jQuery for brevity. It can also be written using vanilla javascript.

Here I took the tracking URL and added it as a data attribute to the anchor tag so that different links can easily have different tracking URLs. I gave the binding a trackme class, which javascript knows to assign a tracking function to that specific tag <a>

.



javascript prevents the href from loading by default until the ajax call succeeds or fails and then it loads the href.

<html>
<head>
<script src='https://code.jquery.com/jquery-3.2.1.js'></script>
<script type='text/javascript'>
$(document).on("click", ".trackme", function (e) {
    e.preventDefault(); // stop browser from going to href right away
    var finalURL = this.href;
    $.ajax({
        url: $(this).data("tracking-url"),
        success: function () {
            location.href = finalURL;
        },
        error: function () {
            location.href = finalURL;
        }
    });
});
</script>
</head>
<body>
<a href="http://google.com" data-tracking-url="http://examplemysite.com/tracking.php?123" class="trackme">anchor text</a>
<a href="http://yahoo.com" data-tracking-url="http://examplemysite.com/tracking.php?124" class="trackme">anchor text</a>
</body>
</html>

      

+1


source







All Articles