GTM V2 DataLayer button click tracking - google-tag-manager

On my webpage I have 3 button ( Good ,Average, Bad). I want to track how many times particular button is click. I want to use custom dimension and custom metric to track this in below format
Button Name No.of time button click
Good 5
Average 10
Bad 5
I have created custom dimension, DataLayer Variable (in GTM V2), custom metric. I am not able to write the DataLayer code (DataLayer Creation & DataLayer Push method) code to track the counts how many time a particular button is clicked as I am not a developer or coder .
Can someone please help me with the code of DataLayer that I can paste/code on my webpage so that click value for button is passed to custom metric I have created. DataLayer name that I have created in GTM V2 is BottonClicKToTrack. Also do I need to define Event for the same.

You don't necessarily need to insert anything into the datalayer to accomplish what you're asking. You can, but I believe there is an easier way.
1) Set up 3 triggers, one for each button. Make each button fire when the respective button is clicked
2) Set up 3 tags, one for each button. Make each tag send an event to your GA Account with the following information.
Category : Button
Action : Click
Label : Good/Average/Bad
This way you will be able to view your button clicks in google analytics and sort them by label to see which one was clicked more. If you have questions about the implementation please comment and I will post a full detailed solution. If you request a full detailed solution, I would like to see your HTML code for the buttons. Specifically I would need to see something like this
<button id='?' class='?'>BUTTON TEXT</button>

Avez,
You need to place the data layer code above your GTM Script tag. Like so.
<body>
<script>
dataLayer = [{
'good': 0,
'average': 0,
'bad':0
}];
</script>
<!-- Google Tag Manager -->
<!-- End Google Tag Manager -->
<button onclick="incrementCounter('good');" id='goodButton'>Good</button>
<button onclick="incrementCounter('average');" id='averageButton'>Average</button>
<button onclick="incrementCounter('bad');" id='badButton'>Bad</button>
<script>
var good = 0;
var average = 0;
var bad = 0;
function incrementCounter(b) {
if (b == 'good')
good += 1;
else if (b == 'average')
average += 1;
else if (b == 'bad') {
bad += 1;
}
dataLayer = [{
'good': good,
'average': average,
'bad':bad
}];
console.log(dataLayer); /* DEBUG STATEMENT */
};
</script>
</body>
I left a debug statement inside of the script so you can see what the function is doing. I'm not a huge fan of this approach but it will work. Installing this script into your page (inside of the body tags) will set up the necessary functionality to record button clicks. From here I am not sure what you are asking for. Perhaps start with this and let me know what else I could do.

Related

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.

Create dataLayer custom event for external clicks

I am looking to create a dataLayer push event for any time a click is made on any external link - I plan to use it as a trigger to fire a GTM tag for external link tracking. I envision it will be something like this :
<script>
Some code to detect clicks on any external links
dataLayer.push({'event': 'eventNameXYZ'});
</script
An example function:
function pushToDataLayer() {
var links = document.getElementsByTagName('a');
for(var i=0,cnt=links.length;i<cnt;i++) {
var current = links[i];
current.onclick = function() {
dataLayer.push({
'href': current.href,
'event': 'outbound' // event to trigger a rule in the tag manager
});
}
}
}
(This will be much easier if you use jQuery or something like it). This will attach an click event to all links. The click will push an event and a variable with the clicked href to the dataLayer.
In the Tag Manager you need to create a new rule that triggers a tag on the custom event "outbound" and a Macro with the type dataLayer that catches the "href" dataLayer Variable. You can use this variable in your tags - for example with a GA virtual ´pageview - and have the tags fire with the rule "fire on event "outbound".
The code might not work on all browsers and is a demonstration of a principle rather than production code (plus it will catch all links, you'd need to test for absolute urls or domains name or css class names that suggest an outbound link). I would recommend using jQuery for finding the links and attaching events.

Firing 2 google analytics events with an outbound link

I have outbound links like this in my html:
<a href="http://www.example.com" class="gaLink1"
target="_blank" onCLick="ga_track_link('action', '123', 'abcde', 'fghij')">
<img src="http://www.example.com/image.jpg" alt="image name" height="180" style="max-width:153px;max-height:150px;" />
</a>
So, When there is a click on this image, the link www.example.com should open in a new tab, since there is target="_blank". Also, the onCLick event will call the function ga_track_link which is defined as:
function ga_track_link(action, id, name, source) {
_gaq.push(['_trackEvent', 'category 1', action, id+': '+name]);
_gaq.push(['_trackEvent', 'category 2', 'example', source, 15]);
}
This function is defined in the script section at the end of the html (inside the body section)
I'm observing in GA, there both events are tracked (category 1 and 2), but the amount of times that both are tracked is not equal. Category 2 appears almost half of times, which makes me think that the 2nd event is not always being fired.
I found this link http://support.google.com/googleanalytics/bin/answer.py?hl=en&answer=55527
that suggests to put the function "ga_track_link" in the head section of the html and use a return False in the onClick function.
According to some other answers like When and why to 'return false' in JavaScript? , the return false statement would tell the event (onClick) not to be fired, which is not what I want, since I do want it to be fired but after my 2 GA events were fired.
So, I have 3 questions:
1) Is there any problem firing more than 1 GA event (with _trackEvent) on 1 click? What is the best way to do it?
2) Why Google Analytics link above states that the function should be placed in the head section of the html?
3) Can someone please clarify the "return false" statement's goal and how to use it correctly?
1) Is there any problem firing more than 1 GA event (with _trackEvent) on 1 click? What is the best way to do it?
No, no issue with that although you could do both with one push. One Push, Multiple Commands
2) Why Google Analytics link above states that the function should be placed in the head section of the html?
Because the user may click the link before the javascript has time to load on the page.
3) Can someone please clarify the "return false" statement's goal and how to use it correctly?
My understanding is that it prevents the default behavior of the element and if listed after your function call it should have no effect on that function call. This is just as stated in one of the answers to the question you cited:
<a href="#" onclick="doSomeFunction(); return false;">
In the Google Analytics support link you provided, the return false; is stopping the link from immediately sending the user off the site. It runs the tracking function before hand and then redirects the user to the external site after a delay. This allows the tracking code the time needed to be sent off before the redirect.
function recordOutboundLink(link, category, action) {
_gat._getTrackerByName()._trackEvent(category, action); //set tracking
setTimeout('document.location = "' + link.href + '"', 100); // redirect to external site after delay
}
Do you have target="_blank" on all links using your ga_track_link() function?
If the link is opening in the same window, it's possible that the tracking pixel requests made by _trackEvent might not have time to complete before the new page starts being fetched. If the link is opening in a new window, it's not a problem.

How to incorporate Google Analytics Event Tracking with Anythingslider

I am looking for some clues on where to add Google Analytics Event Tracking to a page that has AnythingSlider installed. I have a slider that does not autoscroll and you have to click the navigation buttons for the slides to move. I wish to track these clicks. I would also like to track if a visitor clicks on a link within a slide.
I am wishing to use Google's InPage Analytics to track visitor click behavior and workout what items (images & phrases) catch the attention of the visitor in order to make better lead funnels.
I did try the Event tracking guide from Google before posting here, but I was unsure of where to pickup the navigation clicks from the slider.
add this to any a href in your html
onClick="_gaq.push(['_trackEvent', 'Slider','Panelno:x', 'blah']);"
Untested (I'm about to do this myself) but the API suggests to me that I should use the onSlideComplete callback, e.g. (assuming you've set up the names of your panels in an array called pages).
onSlideComplete : function(foo) {
_gaq.push(['_trackEvent', 'Slider','Panelno:'+slider.currentPage, pages[index - 1]]);
}
EDIT: Be careful with onSlideComplete, it seems to fire off too often. Set a var to tell it not to refire, and reset the var with onSlideBegin.
onSlideBegin : function(e, slider) {
refire = 1;
},
onSlideComplete : function(slider) {
if (refire) {
_gaq.push(['_trackEvent', 'Slider','Panelno:'+slider.currentPage, pages[slider.currentPage - 1]]);
refire=0;
}
}

How to track file downloads

I am running a Image gallery website which can be used to download images... say if you call somedomain.com/flowers it will return a zip file containing top 10 flower images....
Now my requirement is to track these downloads.. how can I implement this.. any possibility to use Google Analytics.
Update:
I forgot to add another important thing because of which I can't use custom events...
It is not necessary to always click and download a zip file.... I have created a little app (AIR application) to directly download the file.In that case I can't able to use any GA script... I want to know whether it is possible to use GA in this case if yes then how to implement?
Fire a custom event when the user clicks on the download link.
You need to associate google analytics events with your links. Please read
http://code.google.com/apis/analytics/docs/tracking/eventTrackerOverview.html
http://code.google.com/apis/analytics/docs/tracking/eventTrackerGuide.html
The two basic ways are event tracking (registering the click) and the other is by a virtual 'pageview'. The problem with the first is that clicks are less reliably measured; the problem with the second when the user clicks the link, trackPageview might not have time to execute. One common solution is to use the virtual pageview technique and add a small timer to cause a 100 millisecond delay:
In practice, you need two pieces of js code--one to modify the a href tag by binding the onclick handler to a function, and the other to create that function: (shown first, below)
<script type="text/javascript">
function obl(this) {
try {
var pageTracker=_gat._getTracker("UA-XXXXXXX-X");
pageTracker._trackPageview("a_download_link");
setTimeout('document.location = "' + this.href + '"', 100)
}catch(err){}
}
</script>
<a href="a_download_link" onclick='obl(this);return false;'>Click Here to Download</a>
If you are using the newest (asynchronous GA Code) replace the function above with this one:
<script type="text/javascript">
function obl(this) {
_gaq.push(['_trackPageview', 'a_download_link'+this.href]);
setTimeout('document.location = "' + this.href + '"', 100)
}
</script>
One complication this technique introduces is that it causes your downloads to be co-mingled with your page view totals. As long as you are aware of it, it's trivial to deal with--just create a filter to remove these 'false' page views. Similarly, to actually show the downloads in the GA Browser, you might want to create a separate profile (e.g., 'Downloads') and then create an 'Advanced Segment' by filtering all page views except the download page views.

Resources