Tracking button clicks with Google Analytics and JQuery

by John H
2 minutes

Using jquery it is  very easy to push clicks and events to Google analytics

To make things super convenient I just make a class called 'track'.  The next thing I do is add a data-label attribute on the element that I put information in.  I might include something like the name of the button as well as the page or template it is on or even the url'  

Then in my js I'll configure and send my event.

All in all it looks like this 

CSHTML: Asp.net .Net Core

<a  href="https://www.facebook.com/site_page/"  class="fb track" data-label="social-FB (Footer) @Context.Request.Host@Context.Request.Path"> Goto My FB Page </a>

<script>
$('.track').click(function () { var label = ($(this).data('label') ? $(this).data('label') : 'none'); ga.getAll()[0].send('event', 'Tracked Click', 'tracked_click', 'Tracked Click: ' + label); }); </script>

PHP

<a  href="https://www.facebook.com/site_page/"  class="fb track" data-label="social-FB (Footer) <?php echo $_SERVER['REQUEST_URI']; ?>"> Goto My FB Page </a>

<script>
$('.track').click(function () { var label = ($(this).data('label') ? $(this).data('label') : 'none'); ga.getAll()[0].send('event', 'Tracked Click', 'tracked_click', 'Tracked Click: ' + label); }); </script>

Of Note: You may need to just use the regular ga() send event and not need to get the getAll - This matters if you are also using Google Tag Manager on your site too. If you aren't using Google tag manager you'll just use this

ga('send', {
  hitType: 'event',
  eventCategory: 'Video',
  eventAction: 'play',
  eventLabel: 'cats.mp4'
});

Related Articles

Install Google Analytics in Wordpress

If you want to install your Wordpress script so that it works regardless of the theme you install...

John H John H
2 minutes

Setup Google Analytics with Subdomain

By default all of the traffic that goes to any subdomain shows up as a root traffic.  What if you...

John H John H
~1 minute

Amazon Linux additional SSH users

https://blog.e-zest.com/how-to-add-ssh-users-in-amazon-linux/...

John H John H
~1 minute