简体   繁体   中英

Executing an asynchronous AJAX call when a link is clicked, and then following the link

We have a link on our page of which we want to track the usage. Currently, it's not really a link. It's a <div> tag with a data attribute containing the destination and a click handler bound to it.

When clicked, we send data to Google Analytics, and then trigger a page load with window.location = url after a short delay, so that we're sure that the data has gone through.

This approach works, but it has a major flaw: the clickable element is not actually a link, and behaves like one only in part. For example, I can't use my mouse wheel to click on it and have the link open in a separate tab (as you'd expect), or I can't right click on it and get a menu that is contextual to the link (because it's not a link).

Is there a way to use an <a> tag and get the behavior of a real link, intercept the click event, interact with Google Analytics and then follow the link normally after a small delay (to make sure the data goes through), without having to redirect ourselves and without having to lose functionality?

You can use event.preventDefault() to prevent the link from being followed:

$('a').click(function(e){ 
    e.preventDefault();
    var href = this.href;
    setTimeout(function(){
        window.location = href;
    }, 2000)
});

With new HTML5 standards , couldn't you wrap your <div> in an <a> tag? Then you could do:

Inline:

<a href="yourawesomewebsite.com" id="gaEvent" target="_blank" onclick="_gaq.push(['_set', 'hitCallback', function(){window.location = this.href;}]); _gaq.push(['_trackEvent','category','action','label']);">
    <div id ="blah"></div>
</a>

jQuery:

$('gaEvent').on('click', function(){
    _gaq.push(['_set', 'hitCallback', function(){
        window.location = url; // you'll still have to define this somewhere
    }]);

    _gaq.push(['_trackEvent','category','action','label']);
});

I totally referenced this SO post - Track event in google analytics upon clicking form submit

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM