MultiformeIngegno
MultiformeIngegno

Reputation: 7049

document.getElementById().onclick not working inside Google Tag Manager

I am using a cookie consent management service, calling it via Google Tag Manager (custom HTML tag). Their script has function CookieControl.open(); which opens a sidebar to allow users to change their preferences.

<script src="https://cc.cdn.civiccomputing.com/9/cookieControl-9.x.min.js"></script>
<script>
var config = {
...
...
...
};

CookieControl.load(config);

window.onload = function () {
    var cookiesExist = document.querySelector('#cookies');
    if (cookiesExist) {
        document.getElementById("cookies").onclick =
            function () {
                CookieControl.open();
            };
    }
};
</script>

In my footer, I have added a link <a id="cookies">Cookies</a> which the function in GTM is supposed to target. Unfortunately this is not working and the sidebar does not open when I click on the "Cookies" link. It does sometimes work, randomly, on Safari on the iPad. But it's not consistent. Any ideas why most of the time this doesn't work (but other times it does)?

Upvotes: 3

Views: 921

Answers (1)

iismaell
iismaell

Reputation: 633

This is a working example.

// https://codesandbox.io/s/agitated-leaf-vznep?file=/src/index.js

We attached a click event listener to the button, added an href attribute and prevent its default behavior by using the e.preventDefault function. We also created a dedicated function for the CookieControl.open() method.

You may need to wrap the script inside this event listener to make sure that the document is ready before attaching the click event listener to the button.

window.addEventListener('DOMContentLoaded', (event) => {
    console.log('DOM fully loaded and parsed');
    // move the content of index.js file here
});

UPDATE: Duplicated the script in the stackoverflow sandbox in case the link above expires.

import "./styles.css";

// load cookie control

function openCookieControl(e) {
  console.log("CookieControl open");
  // CookieControl.open();
}

let button = document.getElementById("cookies");

button.addEventListener("click", (e) => {
  e.preventDefault();
  openCookieControl();
});
body {
  font-family: sans-serif;
  color: #000000;
}
<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
    <link rel="stylesheet" href="src/styles.css" />
  </head>

  <body>
    <a href="#" id="cookies">Cookies</a>

    <script src="src/index.js"></script>
  </body>
</html>

Upvotes: 1

Related Questions