SomewhereDave
SomewhereDave

Reputation: 483

How to make GTM Tags wait for some jQuery to be loaded?

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

Answers (3)

SomewhereDave
SomewhereDave

Reputation: 483

While using the dataLayer works, as suggested by others, I also found that my code works using two alterations:

  • Change errenous code: document.querySelector("#toast #toast-msg").innerHTML.length > 0 I forgot the innerHTML attribute
  • In order to ensure that jQuery has loaded I changed the trigger type to gtm.dom, which triggered the event reliably thus far.

Upvotes: 0

Killerpixler
Killerpixler

Reputation: 4050

  1. Make Sure you have the dataLayer initialized in the <head> of your document by including this line of code: <script>window.dataLayer = window.dataLayer || [];</script>
  2. Add this code to your jQuery toasts (or whatever else you want to track) dataLayer.push({'event': 'event_name'});
  3. Create a Custom Event trigger in GTM with the event_name you chose above.
  4. Create a GA Tag of type event with the above trigger

Upvotes: 4

Analytics Ml
Analytics Ml

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

Related Questions