GTM Custom Javascript Variable not working (return function)

291 views Asked by At

I've been looking at this for days now and am totally stuck. The page I am working with looks like this:

<div class="field--item">
<span class="file file--mime-application-pdf file--application-pdf icon-before">
<div class="file-info text-center--mobile"><span class="file-icon"><span class="icon glyphicon glyphicon-file text-primary" aria-hidden="true"></span></span><div class="file-wrapper"><span class="file-name">17840.pdf</span><span class="file-size">94.35 KB</span></div></div>
<span class="file-link"><a href="/dashboard/download/17840/122526" class="resource-button" resource-name="Kennedy's actions in Vietnam in 1962" resource-file-id="122526" resource-file-type="PDF" resource-subject="History" resource-category="">Download</a>
</span></span></div>

The custom variable that I set up looks like this:

function() {
    return document.getElementsByClassName('resource-button')[0].getAttribute('resource-name').text();
}

What I really want to do is set up a variable that pulls in the resource name, when the Download button is clicked. I know to set up the actual click tracking etc. separately, I just can't get this function to pull through anything to the variable other than 'defined'.

Any help or a nod in the right direction would be sooo very much appreciated. Thanks!

2

There are 2 answers

1
Miheo On BEST ANSWER

Try removing the text() function at the end:

function getAttribute() {
  return document.getElementsByClassName('resource-button')[0].getAttribute('resource-name');
}

console.log(getAttribute());
<div class="field--item">
<span class="file file--mime-application-pdf file--application-pdf icon-before">
<div class="file-info text-center--mobile"><span class="file-icon"><span class="icon glyphicon glyphicon-file text-primary" aria-hidden="true"></span></span><div class="file-wrapper"><span class="file-name">17840.pdf</span><span class="file-size">94.35 KB</span></div></div>
<span class="file-link"><a href="/dashboard/download/17840/122526" class="resource-button" resource-name="Kennedy's actions in Vietnam in 1962" resource-file-id="122526" resource-file-type="PDF" resource-subject="History" resource-category="">Download</a>
</span></span></div>

0
JordanKobeWade On

perhaps you can use a click event:

<a href="/dashboard/download/17840/122526" onclick="myFunction(this);">Download</a>

<script>
    function myFunction(elem) {
       var yourAttribute = elem.getAttribute('yourAttribute');
    }
</script>