GTM alt Attribute Variable

1 min read

I have recently been handling analytic tagging at work after the digital analytics employee left. In a pursuit of saving myself some time and applying some software best practices to tagging, I started looking for ways to “DRY” up the tags and triggers I create.

On a recent project, I needed to tag several images that are outbound links. I was able to create a single tag and trigger by using a CSS selector that covered all of the images, but I needed a way to pass image specific data in the event. Typically I could do that with the built-in variable, but images do not have any text in their DOM element. They do, however, have an alt attribute which everyone should be using for accessibility! So I started a quest on gathering the alt to pass in the event.

My first stop was Simo Ahava’s blog, the quintessential resource I have been using while learning this completely new work of digital analytics. Specifically, I went to Simo’s variable guide post where I found a comment from Simo about using a custom JavaScript function to grab the clicked element’s alt attribute:

1function() {
2 return .alt;

This works, but I wasn’t super convinced this was the only solution, and I need something that I can remember (and transfer) easily from container to container. GTM has a lot of options, and I was surprised there is not a built-in alt tag solution. I ended up settling with creating a custom auto-event variable with the type set to Event Attribute and attribute name set to “alt”. Below is an image of the final variable. This works perfectly, and is easy to remember when setting up new containers!