Fire a tag when element is loaded on page (Google Tag Manager) - google-tag-manager

I'm using an Element Visibility trigger to track a value that appears on a page. However, I want to track this value even when the user doesn't scroll to the area of the page where the element is (i.e. when the page is loaded, and the value is displayed below the fold, but the user doesn't scroll down there). Is there a way of doing this?

Suppose that you want to track a value when a certain element is present on the DOM but not depending on the visibility, then there is a 4-steps-way to do it as follows:
Assumption: you know the class or id of the element you are looking for. In the
following example, I will use a class because it allows me to report not just one but a collection of elements being part of the DOM.
We can create a trigger to detect every page visited, without any limitations due to the element we want to track could be everywhere.
Then, we can create a TAGS (called "SCRIPT detect element" on the example) of the type "Custom HTML".
Triggering will be the trigger created in step 1.
Knowing the class of the element we want to track, the script to write will be:
<script>
window.dataLayer = window.dataLayer || [];
// get all elements with a given class name
var els = document.getElementsByClassName("classname-to-look-for");
Array.prototype.forEach.call(els, function(el) {
var evtElementPresent = {
'event': 'wantedElementRendered'
}
// push event per each element.
window.dataLayer.push(evtElementPresent);
});
</script>
At this point, we will be reporting events (with event name = "wantedElementRendered") from the website to the TAG MANAGER every time an element with the classname equals to classname-to-look-for is part of the DOM, despite if it is in the viewport or not.
Now, with that in mind, we need to create a new trigger on TAG MANAGER. This time the type of the trigger will be "Custom Event" and we will make this trigger happen only if the event name is wantedElementRendered.
Final step: Let's create a tag that will create a GA4 event reporting it to google analytics.
Tag name: "Report X Element is present"
Type: "Google Analytics: GA4 Event"
Event Name: the name we want to declare on analitycs, eg: "X-Element-Present".
Triggering: will be the trigger created on step 3 -> "X Element Rendered".
Now, let's take a look how it works:
Final notes:
What if we want to track the presence of a lot of elements on the page without taking into account the visibility of each one, but also taking care of each element representing different things, like products?
Then, we can send to Google Analytics not just an event name each time an element is part of the DOM, but an event parameter as well, with the product ID. This will allow us to create reports in analytics, asking not only how many times a product appears as part of pages, but to refine the question: "How many times X product appears across pages?".
Altering steps 1-4 to contemplate events attributes, that can be done in a beautiful way. If anyone is interested, I am open to sharing this alternative as well.

Related

Can I populate a custom dimension in google analytics from page metadata?

I'm trying to report on website performance for a website with editors in various UK regions (Eg. South-West, North, North-East) that don't map to regions that GA understands.
Is it possible to embed the region into the metadata of the page and then read that via Google Analytics as a hit for a custom dimension? If so how do I format the metadata tag on the page?
You can absolutely do this. On your page, below wherever it is that you have the Google Tag Manager script, you'll want to push your values into the data layer. I recommend something along the lines of the following:
<script type="text/javascript">
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
'uk-region': 'South-West' //As applicable
});
</script>
And then you'll need a couple of things in GTM in order to pick this up. First, create a new Data Layer Variable and populate the "Data Layer Variable Name" with the "uk-region" name I used above, or whatever else you want to identify it with. Give it a useful name like "uk-region" at the top.
In your Google Analytics page view tag then, you'll need to set up the custom dimension mapping. Click the box for "Enable overriding settings in this tag" and a dropdown will appear with "More Settings". Expand the "Custom Dimensions" and click the "+ Add Custom Dimension" button. Specify the number custom dimension you wish to populate under Index and in the value, we'll specify the variable we created with {{uk-region}}.
Test your container to ensure it's getting picked up as it should, then publish to commit the container to your website.

GTM Trigger sequence

How can I achieve this using Google Tag Manager?
I want Tag to fire if user made a seeuence of actions. For instance: visits homepage > visits certain category page > clicks on a button that expands additional content > having that content on screen visible at least 90% for 30sec or more > clicking on a button
... exactly in that order.
I would recommend you to use sessionStorage to achieve this. By passing a value to the sessionStorage for each step in the funnel you want to track you can then trigger an event once the user reached the final step.
This solution will require some javascript skills. Here is code snippet to illustrate what I mean.
var url = 'https://www.startpage.com/second';
var start_page = 'https://www.startpage.com';
var second_page = 'https://www.startpage.com/second';
var third_page = 'https://www.startpage.com/second';
if(url = start_page){
sessionStorage.setItem('funnel', 'step 1');
}
if(sessionStorage.funnel){
var previous_step = sessionStorage.funnel;
if(url === second_page && previous_step === start_page){
sessionStorage.funnel = second_page;
}else if(url === third_page && previous_step === third_page){
alert('Send event');
}
}
First of all, you need to enhance Google Tag Manager (GTM) default behavior, buy making some information persistent. By default, GTM tracks information for the current page, so you need to keep track of users making progress in this funnel across several pages. You will find some good advice and examples in this Simo Ahava article.
Second, you need to create all the relevant triggers and tags, that catch these user actions, and update current user's progress in this persistent variable, when they proceed to the next stage. You also need to consider, if there are any actions, which reset the progress, or you allow the user to take other actions as well in the meantime.
The triggers are the following:
Page view for your main page
Page view for your specified category page(s)
Click trigger on the specified element to expand your content
A visibility trigger with proper settings (reference to element, 90% visibility, 30 seconds time on screen)
Finally, a click on your specified element
You should check the progress, and update it when the proper step is taken, compared to the current state. (E.g. complete step three only when user is already on step 2.)
Obviously, you'll need to write the necessary scripts within several Custom HTML tags, but you can probably generalize the behavior with some helper functions for checking the progress, and storing any updates.

Google Tag Manager - Returning a href from another element when a click tag is fired

I'm working on Google Tag Manager/Analytics for a site, here's an example page that a tag is being fired on:
https://www.forktrucktraders.co.uk/listings/refurbished-combilift-multi-directional-gas/
The tag is fired when the "Send Message" button on the contact form is clicked:
https://imgur.com/a/qTPb3Ci
Right now I've got the event's action returning the URL of the current page the form was sent from, but I'd like to know if it's possible to get the href from the "Visit dealer's website" link on the page, as it would give a faster idea of which dealer the listing is coming from. Probably a long shot to make this happen solely through Tag Manager (if not possibly just a hidden bit of data that just has the dealer's name in on the "Send Message" button) but I'd appreciate any input.
You most certainly can. Off the top of my head something along the lines of the following should work...
It depends on whether you prefer just having the url or breaking it down further.
Just the URL:
Create the following in a custom HTML tag within GTM
<script>
//This selects your desired href:
var dealerURL = document.querySelector(".stm-dealer-image-custom-view a").href;
//This pushes the value into the dataLayer temporarily for use later:
window.dataLayer.push({
event: 'formSubmit',
dealer: dealerURL
})
</script>
Ideally, this should be fired on page load of all your listings pages.
Next create a new User-Defined Variable of the dataLayer var type
within GTM corresponding to dealer, this will store the value to be
pulled through in your event.
Now just change your event action to {{dealer}} (or whatever you
ended up naming the datalayer variable), and this value should be
pulled through in your event.
Getting the dealer name:
Now presuming the href format is always the same across the site you could split this by a delimiter instead:
var dealerURL = document.querySelector(".stm-dealer-image-custom-view a").href;
var dealerSplit = dealerURL.split("/");
var dealer = dealerSplit[4];
The above would leave you with a variable containing the string 'hitec'.
This however is quite prone to breaking if the page path does not always follow the same format, as such it would be better to use RegEx instead.
To answer your specific question, you would need to create a variable to target that specific link element that contains the dealer's website's url. The simplest way is probably to add an id to the <a> element and create a variable in GTM to track it.
I had a quick look at your site and I think you have more problems with the form.
Your even triggers without validating the form, this would lead to extra events.
The event category, action and label could use some work in organizing it to help you analyze the data
You also have a mix of gtag.js and GTM snippet on the page, I would say this is not normal practice, usually, GTM is enough. You can contact me through my profile if you'd like to chat more about it.

GTM - One datalayer for multiple containers

I use Google Tag Manager for several weeks now. Recently I had a special request and I have not found an answer. Is it possible that several containers share the same datalayer? In the Js code of two containers, I tried to give the same name to datalayer : the result is rather surprising ... All tags in each containers are executed twice.
Specifically, I try to send an event in two tags which are in two different containers. I'd like to avoid having maximum countless number call on my onclick (hence the idea of ​​having a single data layer)
It is possible to use the same dataLayer for multiple containers. It is also possible to include a second container through the first one (As a tag).
But the "All pages" rule will fire once for each container included on the page. So if you have 3 containers, every tag fired on "All pages" will be fired 3 times.
(The same is true for other events like "gtm.js"...)
We found a simple solution for this problem. Just include a "page_loaded" event on every page and change the "All pages" rule accordingly:
<script>
var dataLayer = [];
</script>
<!-- Google Tag Manager -->
<!-- End Google Tag Manager -->
<script>
dataLayer.push({"event": "page_loaded"});
</script>
The page_loaded event will only fire once, independent from the number of containers used on the page.
This might be obvious (and I haven't tested it) but have you tried to make a copy of your dataLayer ? If you just add below your datalayer variable an assignment
dataLayer2 = dataLayer
and configure you second container to user dataLayer2 ? That would surely be a PITA with dynamically pushed variables, but everything that is rendered at page load should work.
One way that seems to work for us so far is to rename the datalayer variable of the second container like Eike said. GTM allows you to change the name of the variable when it initializes as explained here: https://developers.google.com/tag-manager/devguide#renaming
To track events on both containers you will have to manually push to each:
var data = {some:'data'};
dataLayer.push(data);
otherDataLayer.push(data);
You can have different triggers on each of the container for selectively fire tracking events to GA or other.

Setting a Dynamic Macro in Google Tag Manager

I have two types Universal Analytics (UA) accounts: a rollup property ID that goes on all subdomains, and a subdomain-specific ID that only appears on that subdomain. There are a total of 7 subdomain properties.
I was wondering, instead of setting up 2 tags (ecomm transaction tag and the regular UA tag) for each subdomain/property - a total of 16 - if I could set up just those two tags and have the UA-ID dynamically changed for the corresponding property.
Example: set up the tag with the id as "UA-XXXXXXXX-{{UA ID}}" where "{{UA ID}}" is defined by me and set with a rule depending on what the current subdomain is. Somewhere - without asking the devs to create a new variable pair - have property one associated to "1", property two associated to "2" and so forth, so that the right tracker is fired on the right subdomain.
Thanks!
I did this via the following workaround:
I created a custom html tag that loads when the DOM is ready ( rule "{{event}} == gtm.dom)
inside that custom tag I put some javascript to determine the subdomain (or whatever dynamic property) and set a variable - let's call it "ua" - accordingly
inside the same tag I push the ua variable and a custom event to the datalayer :
dataLayer.push({
'ua':ua,
'event': 'INIT'
});
I created a macro "UA ID" that gets it's value from the push variable above
I created a rule "on init" ( {{event}} == INIT
I used that rule to fire all subsquent tags (so they would be executed only after the UA variable has been set)
So far (i.e. for the last 2 months) this is working rather well, so it might work for you, too.
Actually I think it will be a lot easier for you if create a lookup table with hostname as a base. Then just add the UA properties for all of your subdomains, each on new row in the lookup table. Afterwards you just use this lookup table as the variable for your UA:
It's a cleaner option to manage a lot of GA properties.

Resources