简体   繁体   中英

Google Analytics: adding onClick, but link already has onClick?

I'm using Google Analytics (Universal) and I'm trying to add the onClick action to a link, but there's already onClick script in place:

<a class="checkout-btn" href="/checkout-start" class="button_control" onclick="return $(this).getForm().sendRequest('shop:on_setCouponCode')">Check out</a>

But I need to add this script for GA:

onClick="ga('send', 'event', 'Header', 'hover', 'Outdoor Barstools');"

How can I get two onClick events on one link? Is it possible?

The easiest (although wrong) way is to use a semi colon, having two commands:

onClick="ga('send', 'event', 'Header', 'hover', 'Outdoor Barstools'); return $(this).getForm().sendRequest('shop:on_setCouponCode')"

The better way would be to never use the onClick HTML attribute and use an external JavaScript file to bind to the click() event of the ID. This improves code maintainability.

Tag becomes:

<a class="checkout-btn" id="foo" ...

Using jQuery, and referencing the ID 'foo' tag:

$('#foo').click(function() {
    ga('send', 'event', 'Header', 'hover', 'Outdoor Barstools');
    return $(this).getForm().sendRequest('shop:on_setCouponCode');
});

This is one of the reasons why adding a handler directly in the HTML is sub-optimal. If you are using jQuery, you could use the bind method, for example:

$(".checkout-btn" ).bind( "click", function(evt) {
       console.log('oh yeah');         
});

If you are just using raw JavaScript, it's something like this:

document.getElementById("checkout-btn")
        .addEventListener("click", function(evt) {
       console.log('oh yeah');         
}, false);

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