Analytics
2.2K members online now
2.2K members online now
Dive into multiple domain (Cross/Sub) tracking, implementing Ecommerce and Enhanced Ecommerce, setting up Event tracking, and Universal Analytics code.
 
Guide Me
star_border
Reply

Click event on nested span within button, but data attribute on button

Visitor ✭ ✭ ✭
# 1
Visitor ✭ ✭ ✭

Hi, I've been trying to track click events on a button which has a data-attribute on it I want to use as the label. However, within the button, there are some nested span elements. If I remove these spans, the GTM trigger works perfectly and sends the data attribute to GA. With the span elements nested, the click event registers the span and not the button, and therefore can't access the data attribute I'm targetting. Is there a way to do this within the GTM config? 

 

E.g markup

<button data-event="myevent" data-sku="123"><span>Click</span</button>

 

Thanks!

1 Expert replyverified_user

Click event on nested span within button, but data attribute on button

Top Contributor
# 2
Top Contributor

Hi, bsod99,

 

The <span> tag is a non-semantic HTML element and you should avoid using it. In the context of your button, you should be able to trigger the click without the span tags, as you've already observed. The text of the button (without the <span> tags) should be sufficient for all intents and purposes, as far as semantics goes. However, if you, for some reason, need the spans, then you might have to create a custom JS variable that scrapes for your data attribute, since you've already noticed that clicking on the <span> tag does not fire your tag.

Nicky Yuen, Google Analytics Top Contributor
Was my response helpful? If yes, please mark it as the ‘Best Answer.’ Learn how here.
Find me on: Google+ | LinkedIn

Click event on nested span within button, but data attribute on button

Visitor ✭ ✭ ✭
# 3
Visitor ✭ ✭ ✭

Hi Nicky Y,

 

Thanks for the reply. The nested span approach is the default button markup in Magento, unfortunately. I could change this but then I'd be obliged to change the markup for all buttons throughout the site to avoid having an inconsistent approach. There's also the use of the <i> tag for icons, so even removing the spans would still leave the same issue if the click is directly on the icon. I guess the icon could just be output via a pseudo element.

 

It's a trade off really between whether I just add the necessary JS to scrape the data attributes needed, or rework the buttons so that GTM can fully handle the events without any custom JS being needed.