Killerpixler
Killerpixler

Reputation: 4050

Google Tag Manager custom javascript to get data layer variable

I want to do some processing on a data layer variable before I want to use it in a tag. for instance I have a number of social icons with the fontawseome framework. Now I want to create a variable that gives me which one is clicked.

How do I get the part of the data layer elementClasses value?

In preview mode I can see that when I click on a button the Data Layer values after this message box looks like this:

{
  gtm: {
    ...
    ...
    elementClasses: 'fa fa-twitter',
    ...
  }
}

I essentially want to make a GTM variable of type Custom JavaScript that does this

function(){
  return elementClassesString.match(/fa-.*/);
}

Any tips?

EDIT::

In the console I can get the latest data layer entry by typing dataLayer[dataLayer.length-1] so I figured this would do the trick:

function(){
  latest = dataLayer[dataLayer.length-1]["gtm.elementClasses"];
  if(latest === ""){
   social = "not-set" 
  }else{
    social = latest.match(/fa-.*/)[0];
    social = social.substring(3,social.length);
  }
  return social;
}

But I only get undefined in the GTM preview. Why is that?

Upvotes: 0

Views: 2027

Answers (1)

nyuen
nyuen

Reputation: 8907

To get the gtm.ElementClasses when it's pushed (ie. in gtm.click or gtm.linkClick events") you can create an Auto-Event variable like this:

enter image description here

This variable returns the class of the element that is clicked. You can then use this variable in other custom JS variables.

Upvotes: 1

Related Questions