Reputation: 65
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?
Upvotes: 0
Views: 1319
Reputation: 7289
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);
Upvotes: 0
Reputation: 910
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');
});
Upvotes: 1