views:

27

answers:

2

Hi,

Im having trouble with a onclick event for a download. It does not want to fire when I click on the link. It just carries on as normal. But it does work with an external link. Have I done something obviously wrong?

<a href="http://www.wildlifetrusts.org/" target="_blank" onclick="trackExternalLink(this, '/links-the_royal_society_of_wildlife_trusts');">Royal Society of Wildlife Trusts.</a>
<a href="/c2/uploads/our strategy for 2010_15.pdf" target="_blank" onclick="trackExternalLink(this, '/downloads-our_strategy_for_2010-15');">2010-2015 strategy,</a>

Its doing the same in FF, Chrome and IE 8.

function trackExternalLink(link, action) {
_gaq.push(['_trackPageview', action]);
setTimeout('document.location = "' + link.href + '"', 25000)
return false;
}
A: 

I beleive you need to return false to prevent the click from fucntioning as normal, this may, however, be jQuery specific.

I would also recomend using a framework rather than onclick attributes, they're messy and the framework will also be helpful in other respects.

thomasfedb
I am returning false in my function. I previously had it inline but it made no difference.
YuppieGuppie
A: 

You're not returning false from your onclick handler. You're returning false from the function it calls, but then throwing that away in the handler. You meant:

onclick="return trackExternalLink(this, '/links-the_royal_society_of_wildlife_trusts');"

However all this onclick stuff is pretty ugly. Consider unobtrusive scripting. And lose the nasty call to setTimeout creating script from a string. Do Google really recommend this code? It kinda sucks.

Here's a quick hack version that wraps the action into a class name:

<a href="http://www.wildlifetrusts.org/" class="ping-links-the_royal_society_of_wildlife_trusts">Royal Society of Wildlife Trusts.</a>

<script type="text/javascript">
    for (var i= document.links.length; i-->0;)
        if (document.links[i].className.substring(0, 5)==='ping-')
            document.links[i].onclick= pingclick;

    function pingclick() {
        var action= this.className.substring(5);
        var href= this.href;

        _gaq.push(['_trackPageview', action]);
        setTimeout(function() {
            location.href= href;
        }, 25000);

        return false;
    }
</script>

This still isn't great. 25 seconds (25000) is obviously way too long a delay; you probably want to pull that down to around 200ish. Really it should be following the link as soon as the XMLHttpRequest that passes the information to the server is complete, rather than using an arbitrary delay, but Google don't seem to give you that option. How poor. Then again, link-tracking pingback scripts are a nasty, user-hostile activity anyway.

bobince

related questions