Gancena Gancena - 1 year ago 65
CSS Question

jQuery - I want to pull html5 data-attribute values from a particular element class into an onclick attribute value

I am assigning a css class

to specific elements I want to track while also assigning data-attributes
, etc to specific elements as well.

Example :

$('a, button, form, input').addClass('ga-track');

'data-category':'Form Submission',
'data-label':'Specific FormID Label'

The data attributes and the classes get added correctly.

Now I am trying to imbed an inline Google Analytics onClick event by targeting all elements with the class
by doing
.attr('onclick', '_gaq.push('_trackEvent', ...')
as you can see in the snippet below.

$(".ga-track").attr("onclick", "_gaq.push('_trackEvent','"$(this).data('category')"','"$(this).data('action');"','"$(this).data('label');"','"$(this).data('value');"','"$(this).data('interaction');"');");

I am unsure about the ability to do data-attribute calls in a .attr() function.

I also tried doing
.attr('onclick', myFunction())
and then binding the
to the _ga.push calls in jQuery but it looks like I'm being forced to append an onclick event with the onclick event set inline with the element I'm attempting to target.

Answer Source

You should not use the onclick attribute with jquery, instead use the .click() function or .on('click',..) and a callback function:

$('.ga-track').on('click', function(){
   _gaq.push('_trackEvent', $(this).data('category'), $(this).data('action'), $(this).data('label'), $(this).data('value'), $(this).data('interaction'));

Whats also problematic:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download