Google Event Tracking Using jquery multiple events

85 Views Asked by At

Complete novice and surprised to get this far, using google and youtube.

<script type="text/javascript">
    window.onload = function() {
        jQuery('.apply_now_green, .apply_now_red, .feat_lender img, .feat_lender h3').click(function() {
            var label = jQuery(this).parents('.col-md-3').find('h3').text();
            ga('send', 'event', 'apply now button', 'click', label);

        });
    };
</script>

<script type="text/javascript">
    window.onload = function() {
        jQuery('.more_details').click(function() {
            var label = jQuery(this).parents('.col-md-3').find('h3').text();
            ga('send', 'event', 'more details', 'click', label);

        });
    };
</script>

How can I merge the two, in the current format it wont work on analytics for tracking the two different events.

1

There are 1 best solutions below

0
On

You can make use of HTML5 data attributes to save your Analytics category/other data on the element itself.

In jquery you can do something like this:

$('.clickable').on('click', function() {
  var gaCategory = $(this).data('category');
  var gaLabel = $(this).data('label');
  
  alert('Category: ' + gaCategory + ', Label: ' + gaLabel);
});
.clickable {
  width: 50px;
  height: 50px;
  background: green;
  margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="clickable" data-category="category1" data-label="label1"></div>
<div class="clickable" data-category="category2" data-label="label2"></div>
<div class="clickable" data-category="category3" data-label="label3"></div>
<div class="clickable" data-category="category4" data-label="label4"></div>