Reputation: 483
I would like to track if a toast (or any "popup element") gets displayed using Google Analytics Event Tracking via GTM. Whether or not the toast gets displayed is defined by jQuery code and based on cookie information like so
function ShowToast(Msg){
$('#toast-msg').html(Msg);
$('#toast').animate({ left: '-10px' });
}
called by
<script type="text/javascript">
$(function() {
ShowToast("SOME HTML");
});
</script>
This is what I got in GTM so far using a custom variable
function(){
if(document.querySelector("#toast #toast-msg").length > 0){
return true;
}
}
with a trigger listening for this variable to be true and the usual Universal Analytics Event Tag. The idea is to simply check if the toast-msg is shown or not, which works fine in preview mode.
Now to the problem: The tag is listening to gtm.js (pageview), but the jQuery code from the toast might load only after gtm.js is ready. Hence, sometimes the toast is not yet displayed when the tracking code is ready to fire and the event is not recorded.
Is there a way to use GTM and Javascript / JQuery to make sure all JQuery is loaded before GTM variables/triggers/tags are resolved? Or a completly different approach?
Upvotes: 4
Views: 8006
Reputation: 483
While using the dataLayer works, as suggested by others, I also found that my code works using two alterations:
document.querySelector("#toast #toast-msg").innerHTML.length > 0
I forgot the innerHTML attributeUpvotes: 0
Reputation: 4050
<head>
of your document by including this line of code: <script>window.dataLayer = window.dataLayer || [];</script>
dataLayer.push({'event': 'event_name'});
Custom Event
trigger in GTM with the event_name
you chose above.Upvotes: 4
Reputation: 598
One method is to push an event to dataLayer when the popup is loaded. the other method is you can fire your code and gtm.dom or gtm.load(when the page is completely loaded)
Check the related article for more details http://marketlytics.com/analytics-faq/control-gtm-tags-to-wait
Upvotes: 0