andruil
andruil

Reputation: 3

Capture the on-click ID of an element, then append it to an outgoing URL using GTM

I am trying to append outgoing links to a specific domain with some UTM information using Google Tag Manager.

I have successfully rewritten the html on pageload with the following:

<script type="text/javascript">
//
var myDomain = "www.target.com";
//
var links = document.getElementsByTagName('a');
// Loop 
Array.prototype.forEach.call(links, function (link) {
// Link check
if ( link.href.indexOf(myDomain) > 0 ) {
   // Take the href and append the UTM parameters
   link.href += "?utm_source=" + {{UTMsource}} + "&utm_campaign=target_blog&utm_medium=" + {{UTMmedium}} + "&utm_term=&utm_content=";
}
});
</script>

{{UTMsource}} is capturing the current page URL. I'm not able to get the {{UTMmedium}} to capture the id of the on-click element a user clicks on when leaving the site.

I can capture the text of the element with the following CSS Selector: a[href*="target.com"] However, if there are multiple links on the page it will only get the text from the first link found on the page.

I want to capture the id of the element being clicked on, and then have {{UTMmedium}} capture that information to be included in the UTM code on the outgoing link.

Upvotes: 0

Views: 928

Answers (1)

sdhaus
sdhaus

Reputation: 1896

The problem you are experiencing is because GTM is running your HTML tag on pageload.

Because the variable (UTMmedium) has not had a chance to be populated (no click event), this value will be undefined.

An additional problem is that GTM would only have collected a single static value, then would input that single ID on all links on load.

Instead of using a variable, modify your loop and capture the id using js whilst capturing the href, as below:

// Link check
if ( link.href.indexOf(myDomain) > 0 ) {
   // Take the href and append the UTM parameters
   link.href += "?utm_source=" + {{UTMsource}} + 
   "&utm_campaign=target_blog&utm_medium=" + link.id + 
   "&utm_term=&utm_content=";
    }

Upvotes: 1

Related Questions