LocustHorde LocustHorde - 3 months ago 44
Javascript Question

Delay href click, but not with SetTimeout

I am trying to track the outbound links via google analytics, and Google suggests using this:

<script type="text/javascript">
function recordOutboundLink(link, category, action) {
_gat._getTrackerByName()._trackEvent(category, action);
setTimeout('document.location = "' + link.href + '"', 100);
}
</script>


Which is fine, except, my outbound links are to be opened in a new tab, and I am (naturally) using a
target="_blank"
for that..

but, the
setTimeout
method takes that away, and opens the link in the same page..

I've tried using
window.open()
but I am worried that it will be blocked by browsers..

So, is there anyway that I can execute this js function, and delay the click for just a little while? (100ms as google suggests)?

Thanks.



I've looked at other questions like this on SO, but they don't deal with opening in new tab/window.

Answer

Ok to evolve the answer above here is a Jquery plugin that can provide listen a selection of links (based on your own criteria) and provide you a method for callback to them.

fiddle

So in the OP's case the setup could look like:

<a href="http://www.google.co.uk" target="_blank" data-category="Outbound">Google</a>

$(document).ready(function() {
    $('a').trackOutBound(null,function() {
        var category= $(this).data('category');
        _gat._getTrackerByName()._trackEvent(category, $(this).attr('href'));
    });
});
Comments