Search code examples
google-analyticsonclicksyntax-erroruniversal-analyticsevent-tracking

OnClick - Uncaught SyntaxError: Invalid or unexpected token


I'm having trouble getting an OnClick event to send back to Google(Universal) Analytics.

Here's the line in question:

<a href= “link-to-asset-goes-here” onclick="ga(‘send’, ‘event’, ‘Button’, ‘Click’, ‘AllVisits_Free’, {‘NonInteraction’: 1});”>

When I inspect with Chrome Dev tools, I'm seeing this error: "Uncaught SyntaxError: Invalid or unexpected token"

When looking through other questions, I found this one:java - OnClick error

Could it possibly be just escaping all the strings then? Like so:

<a href= “link-to-asset-goes-here” onclick="ga(\‘send’\, \‘event’\, \‘Button’\, \‘Click’\, \‘AllVisits_Free’\, {\‘NonInteraction’\: 1});”>

Would that cause any issues with the NonInteraction part of the code?

Unfortunately I don't have access to test this live, and have to send each code revision over to the client each time, or I could just test different variations of code a lot easier.

And just for reference, we're using the newest version of GA(Universal) analytics tracking code. When looking at the Real Time reports in GA, it's registering that I'm on the page, but events are not firing when clicking the link.

Thanks!


Solution

  • If that it the exact code format you are using, then try using straight quotes rather than the smart quotes:

    <a href= "link-to-asset-goes-here" onclick="ga('send', 'event', 'Button', 'Click', 'AllVisits_Free', {'NonInteraction': 1});">
    

    ....Something with smart quotes not playing well with JavaScript.