Search code examples
javascriptevent-tracking

Event tracking code in Javascript


I am adding GA Event tracking code and listening for clicks.

In the below code I am creating the links dynamically using Javascript:

<c:forEach items="${higherStudiesSubCategory}" var="sub">
                           databb1=databb1 + '<a class="col-xs-4 Cfilter" id="higherstudies,${sub}" onclick="GetResultAccordingToSubCategory(this)">${sub}</a>';
                           option1=option1 + '<option value="${sub}">${sub}</option>';
                           $('#subcategory-menu').html(option1);
                           $('.category-all-filters').html(databb1);
                        </c:forEach>

After adding Event tracking code :

<c:forEach items="${higherStudiesSubCategory}" var="sub">
                           databb1=databb1 + '<a class="col-xs-4 Cfilter" id="higherstudies,${sub}" onclick="ga(send,event,SubCategory,click,'+location+':${sub});GetResultAccordingToSubCategory(this)">${sub}</a>';
                           option1=option1 + '<option value="${sub}">${sub}</option>';
                           $('#subcategory-menu').html(option1);
                           $('.category-all-filters').html(databb1);
                        </c:forEach>

The difference in the above code is the onclick function :

onclick="ga(send,event,SubCategory,click,'+location+':${sub});GetResultAccordingToSubCategory(this)"

But the above code does not fire the event (tracked through omnibug) as single quotes is missing in the above code. It should be:

onclick="ga('send','event','SubCategory','click','+location+':${sub});GetResultAccordingToSubCategory(this)"

But using the single quotes in the code gives javascript error. Please help me how can i add single quotes in my javascript onclick function?


Solution

  • Try this:

    '<a class="col-xs-4 Cfilter" id="higherstudies,${sub}" onclick="ga('+"'send'"+','+"'event'"+','+"'SubCategory'"+','+"'click'"+',\''+location+':${sub}\');GetResultAccordingToSubCategory(this)">${sub}</a>';