How to track events by Google Analytics ?

Daniel WANG
GA & SEO Record
Published in
2 min readFeb 11, 2018

--

There are several version of tracking code. I will use the latest one as example.

1. Where is the Tracking code?

You can find it in your Google Analytics admin interface like following pic.

The latest version is gtag.js. Before this version was analytics.js, and further ga.js. Official document highly recommend to change the latest one if you are still use the old version.

So, copy this script and paste in your website before </body>.And first step is done. It’s simple, isn’t it?

2. Let’s start tracking!!

Use the following line of code to define the event group. Don’t worry ,it’s easy.

For example:

There are couple of buttons want to be tracked. each button click means a merchandise is browsed by someone.

gtag(‘event’, ‘product_browsed’, {‘event-category’: ‘mobile phones’ ,‘event_label’: ‘iPhone7’ });

or

gtag(‘event’, ‘product_browsed’, {‘event-category’: ‘mobile phones’ ,‘event_label’: ‘Galaxy S3’ });

or

gtag(‘event’, ‘product_browsed’, {‘event-category’: ‘laptop’ ,‘event_label’: ‘Mac Book Air 13’});

Now you know that three lines of code present different buttons. Put them to html or js. I will explain how to do it in next paragraph.

3. How to let these code work? Where should I put them?

The basic rule is that if the code is executed by the browser which means the event is happening now. So how to make that happen? We usually need some html or javascript knowledge.

Common Html Tag Attributes

1. onclick =’traking code’

Usually use to track <button> or <a> html tag.

<button onclick=”gtag(‘event’, ‘product_browsed’, {‘event-category’: ‘mobile phones’ ,‘event_label’: ‘Galaxy S3’ });”><button onclick=”gtag(‘event’, ‘product_browsed’, {‘event-category’: ‘mobile phones’ ,‘event_label’: ‘iPhone7’ });”>

When visitors click these buttons. It will be tracked by Google analytics.

2. onload =’traking code’

Usually use to track <img> html tag.

<img src="iphone7.jpg" onload=”gtag(‘event’, ‘pic_browsed’, {‘event-category’: ‘mobile phones’ ,‘event_label’: ‘iPhone7’ });”>

When this pic load by browser, It will be tracked by Google analytics.

There are more way to trigger script. ex: “onfocus”, “onchange” . What ever you guys want. In addition,You can also put in the javascript to customize your demand.

4. How do I know that work or not?

Open the Admin interface -> real time -> event

Just Click!! You can see the Right now become 1, and which button did you click. If it is not work, check the code again.

--

--