Reputation: 2605
Im using an onClick event to push a data layer to Google Tag manager but I also want to send the user to a page using the a href
. Because of this I don't think my event is being recorded in Google Analytics because the page has been redirected before the event has been recorded.
JS
$(document).ready(function () {
$('.gtm-click-evt').click(function(){
var dataAmount = $(this).data('value').replace("$", ""); //Remove dollar sign
var value = parseInt(dataAmount); //convert to int
dataLayer.push({
'event': 'clickEvent',
'category': $(this).data('category'),
'action': $(this).data('action'),
'label': $(this).data('label'),
'value': value
});
});
});
HTML
<a href="/want-to-also-redirect-to-a-page"
class="gtm-click-evt gtm-colo btn btn-primary bg-green"
data-category="productClick"
data-action="colocationClick"
data-label="label"
data-value="99">
Buy Now
</a>
Upvotes: 1
Views: 1551
Reputation: 168
Stop the default action (event.preventDefault();) run your essential code and then wait for a second and redirect.
$(document).ready(function () {
$('.gtm-click-evt').click(function(event){
event.preventDefault();
var dataAmount = $(this).data('value').replace("$", ""); //Remove dollar sign
var value = parseInt(dataAmount); //convert to int
dataLayer.push({
'event': 'clickEvent',
'category': $(this).data('category'),
'action': $(this).data('action'),
'label': $(this).data('label'),
'value': value
});
url=$(this).attr('href');
setTimeout(function(){location.href = url}, 1000);
});
});
Upvotes: 1
Reputation: 81
You can just redirect the user to the page in the function:
$(document).ready(function () {
$('.gtm-click-evt').click(function(){
var dataAmount = $(this).data('value').replace("$", ""); //Remove dollar sign
var value = parseInt(dataAmount); //convert to int
dataLayer.push({
'event': 'clickEvent',
'category': $(this).data('category'),
'action': $(this).data('action'),
'label': $(this).data('label'),
'value': value
});
window.location = "/want-to-also-redirect-to-a-page";
});
});
And then the link change:
<a class="gtm-click-evt gtm-colo btn btn-primary bg-green"
data-category="productClick"
data-action="colocationClick"
data-label="label"
data-value="99">
Buy Now
</a>
Upvotes: 1