Florian
Florian

Reputation: 115

How to create on-click events for google analytics with javascript

I'm using generate press theme and elementor in wordpress and now we need to create on-click events for the menu and the buttons, see. Since I can't really use the html way to do it, I will need to use javascript. I've tried it like this:

<script>
     (function($){
         $( "#landingpage3-button1" ).click(function() {
             ga('send','event','phone call','header');
         });
     })(jQuery);
</script>`

However this doesn't seem to work...

Any ideas how to fix this?

Best regards,

Florian

PS: I don't really know javascript and got this code from someone else...

Upvotes: 1

Views: 4011

Answers (2)

Tushar Gupta
Tushar Gupta

Reputation: 15913

Oki so there are various ways to implement tags. If you need to go for hard coded events, i.e. firing from JS, you can do that :

  • Create a onClick attribute in your tag
  • Make your Analytics.js is included and instantiated before you call this function

The above code you have posted must also work, make sure your analytics.js has been pushed before and ga object is instantiated.

USe binding function on click, as it migth be the case js goes on before your DOM is loaded, and it will not be binded. So use like below:

(function($){
       $( "#landingpage3-button1" ).on('click', function() {
           ga('send','event','phone call','header');
       });
})(jQuery);  

Using GTM:

  • You can create a click event which is pretty easy.
  • If you have two GTM accounts, either use one or use both but make sure the tags are not duplicated.
  • I work in an agency as well. Best practice is to have a single GTM and publish altogether. It would take some time but will make your life easier at the later stage.
  • GTM has workspaces. If you need, just work on different workspace than the agency one.

PS: If the agency is working with you, ask them to implement the tags for you.

Upvotes: 2

Julia
Julia

Reputation: 48

It looks like you could use help learning event tracking with Google Tag Manager. You can use tags to track anything in Google Analytics. Here is a short video explaining how. https://www.youtube.com/watch?v=iaJ9HHvKeL8

Upvotes: 0

Related Questions