Firing 2 google analytics events with an outbound link - onclick

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.

Related

Tracking user link clicks with google analytics

I have created an affiliate marketing website. Here users will register on my website and shop, however the shopping link will be of amazon.
I need to know how to set up Google Analytics so that it can track which registered user has clicked an affiliate link on my website.
For example I have this amazon link
https://www.amazon.in/BassHeads-225-Super-Extra-Headphones/dp/B01M9C51T9/ref=sr_1_1?_encoding=UTF8&pf_rd_i=desktop&pf_rd_m=A1VBAL9TL5WCBF&pf_rd_p=14ffe21a-e5a2-45c9-a9c0-91f47b082bbc&pf_rd_r=94G5Y8CM93G8M5Y2SNS3&pf_rd_t=36701&qid=1554008093&s=gateway&smid=A14CZOWI0VEHLG&sr=8-1
I know I'm supposed to put an onClick event on there somewhere but I don't have any idea how it links to Google Analytics? I am using Google Tag Manager
Is this the correct Onclick code:
onClick="_gaq.push(['_trackEvent', 'Link', 'Click', 'Banner Advert1']);"
If not what do I need to add to track the registered user?
I have many links to external sites on my website; an example link looks like this:
<a id="Buy" data-itemDescription="(a description)" data-itemValue="2.80" href=http://externalsite?id=6789>
The key things here are the extra attributes before the href: id (used to identify the specific event that occurs when the link is clicked, i.e. in this case a Buy event) and the data-itemDescription and data-itemValue metadata (used in constructing the event label etc.)
The relevant GTM artefacts are as follows:
Trigger:
Buy: Click - Just Links when Click Id contains Buy
User-defined variables (custom Javascript):
ItemDescription:
function() {
return {{Click Element}}.getAttribute("data-itemDescription");
}
ItemValue:
function() {
return {{Click Element}}.getAttribute("data-itemValue");
}
ItemValueFloat (100 multiplier used because GA didn't like my decimal places - I then divide by 100 at reporting time to get the right answer):
function() {
return parseFloat({{ItemValue}})*100;
}
Tag BuyClicked is an Event triggered by the Buy trigger as above, with:
Category = Purchase Tracking
Action = Purchase {{ItemDescription}}
Label = {{Page Path}} : {{Click URL}}
Value = {{ItemValueFloat}}
I also have Non-Interaction Hit set True.
The BuyClicked event is then collected by GA, and reportable on from e.g. Google Data Studio, without my having to do anything further.
If you can't add an id or metadata, you could undoubtedly do the same sort of thing more painfully by handling all clicks through a single trigger and then parsing the Click URL via custom Javascript to get granular Categories, Actions, Labels.

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.

Google Analytics Event Tracking - Not working for a download link

I just finished working on a plugin for Sketch and I created a simple landing page for users to download the plugin. I want to use Google Analytics event tracking to track the downloads, but the event tracking is not working and I can't seem to figure out why.
Here is what the link looks like:
Download
Does anyone see what I'm doing wrong? Do I need to add any other code anywhere else besides the onclick attribute?
My bet is that you're facing what we call a race condition: the moment the user clicks the link, the browser initiates a page change, thus GA is interrupted before it's had a chance to send the event.
2 options
Open link in new tab: add target="_blank" to your links so they open in a new tab and don't interrupt GA in the current tab.
Prevent Default + Hitcallback: you can use a custom function for onClick that will prevent the link from opening by default (return false;), trigger the GA event, and use GA's hitCallback to trigger the page change programatically.
For option 2 there are different ways of doing it (since it's custom code). Here is an example from Google:
https://support.google.com/analytics/answer/1136920?hl=en
<script>
/**
* Function that tracks a click on an outbound link in Analytics.
* This function takes a valid URL string as an argument, and uses that URL string
* as the event label. Setting the transport method to 'beacon' lets the hit be sent
* using 'navigator.sendBeacon' in browser that support it.
*/
var trackOutboundLink = function(url) {
ga('send', 'event', 'outbound', 'click', url, {
'transport': 'beacon',
'hitCallback': function(){document.location = url;}
});
}
</script>
You'll also need to add (or modify) the onclick attribute to your links. Use this example as a model for your own links:
Check out example.com

GTM V2 DataLayer button click tracking

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.

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