Is there an easy way to track all button clicks?


#1

Hi everyone,

The link click tracking is very useful for my use case. Is there any fairly easy way to track all button clicks as well? I was reading the link click code in the JS tracker but it doesn’t seem trivial at all. Hacking the tracker would be my last option since I’m not a JS developer.

I also saw this issue but there’s not much activity apparently.

Has anyone done this?

Thanks in advance.


#2

@pacuna, the link tracking can only work on <a> tags (with href attribute) at the moment. To allow buttons tracking that are not implemented as HTML links you would have to trigger trackLinkClick method manually on onclick event with the relevant data. That does mean some basic Javascript knowledge.


#3

Thanks for answering. I’m aware of what you say. My question is more related to how to track click to all buttons without having to attach onclick events to every button on the site. Just like the enableLinkTracking which automatically tracks clicks on every link. Could I put a JS snippet on tag manager that fires a custom event for every button click or something like that?

Thanks.


#4

@pacuna, you can add an identifier to all the buttons to be tracked like class=trackable or some distinguishing attribute, <button trackable> and attach a listener to HTML elements identifiable by those. If all the <button>s are to be tracked just add the listener to listen to onclick event to <button> elements.

<script>
buttons = document.querySelectorAll('button')

buttons.forEach(function(elem) {
  elem.addEventListener("click", function() {
    url = elem...
    other_properties = ...
    snowplow('trackLinkClick', url, ...);
  });
});
</script>

#5

Thanks! That’s what I was looking for :grinning:


#6

You can also do this in a tag manager if you want (e.g., GTM) by using an all clicks trigger and firing only on some elements where tagName = 'BUTTON'.


#7

Nice! I’m actually using GTM and I wasn’t aware of this.
Thanks! @mike