I have the below javascript code where I am pulling the destination URL and Alt attribute from the HTML element and trying to push the values in the data-layer.
I have tested the code using the console and it's pulling the desired value. my main concern is how do we push the values in data-layer. Do I need to make modifications to the code to be able to run in customHTML via GTM?
var divHead= document.getElementsByClassName('card__media-overlapping__media');
var eventhandlerdoc = function(event){
var imgURL=event.currentTarget.firstElementChild;
var imgALT=event.currentTarget.firstElementChild.firstElementChild.getAttribute('alt');
dataLayer = [];
dataLayer.push({
'expImgurl': imgURL,
'expImgalt': imgALT
}
for(var index=0; index < divHead.length; index++){
divHead[index].addEventListener('click',eventhandlerdoc,true);}
Your code as-is will break GTM if it is executed after the GTM snippet (since GTM amends the dataLayer's push method with custom code and adds several events). So you would need to make sure this is executed before the snippet, or check if the dataLayer is initalized and reuse it:
window.dataLayer = window.dataLayer || [];
Also the variables will only be available after the next event is pushed to the dataLayer, so you either need to push a custom event or wait until the next (GTM) event before you use them.
And since GTM has it's own click handler I would suggest you use that and move the javascript code to retrieve the attributes to a custom javascript variables.