Search code examples
google-analyticscustom-data-attributeevent-tracking

Get data attribute into event tracking


I have a button

<button data-z="myvalue">
click
</button>

which clicks i want to track in Google Analytics (Universal - analytics.js).

I try it with

<button data-z="myvalue" 
onClick="ga('send', 'event', 'clickout', 'buttonclick', window.location.href, getAttribute('data-z'));>
click
</button>

With window.location.href i get the current URL (work), and with getAttribute('data-z') i want to get the myvalue from data-z (doesn't work).

Any help is appreciated!

PS: JQuery based solutions are welcome!


Solution

  • You are not telling your getAttribute method to which element the attribute belongs - getAttribute does not exists on its own, it is a method of a DOM object (your button in this case).

    Since you are using inline Javascript the DOM object will be available by using the "this" keyword in the click function to call the getAttribute of the button:

    <button data-z="myvalue" 
    onClick="ga('send', 'event', 'clickout', 'buttonclick', window.location.href, this.getAttribute('data-z'));>
    click
    </button>
    

    Much less expensive than jQuery selectors (however using jQuery you could dispense with inline scripts and attach the click in an javascript function. Mixing HTML and JS is not elegant).