Gancena Gancena - 1 month ago 9
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

.ga-track
to specific elements I want to track while also assigning data-attributes
data-category=""
,
data-action=""
,
data-label=""
,
data-value=""
, etc to specific elements as well.

Example :

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


$('form#formid').attr({
'data-category':'Form Submission',
'data-action':'Click',
'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
.ga-track
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
myFunction()
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

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: