How to run Google Analytics code when cookies are accepted?

Hello,

can someone let me know how to run the Google Analytics tracking code when someone accepts the cookies?

Here is the JS code for the cookie banner I created:

let cookieModal = document.querySelector('.cookie-consent-modal');
let cancelCookieBtn = document.querySelector('.btn.cancel');
let acceptCookieBtn = document.querySelector('.btn.accept');

cancelCookieBtn.addEventListener('click', function () {
  cookieModal.classList.remove('active');
});

acceptCookieBtn.addEventListener('click', function () {
  cookieModal.classList.remove('active');
  localStorage.setItem('cookieAccepted', 'yes');
});

setTimeout(function () {
  let cookieAccepted = localStorage.getItem('cookieAccepted');
  if (cookieAccepted != 'yes') {
    cookieModal.classList.add('active');
  }
}, 2000);

The Cookie Banners works just fine, but now I need to add the Google Analytics tracking code when cookies get accepted.

I guess I need to save it in the local storage, right?

  localStorage.setItem('cookieAccepted', 'yes');

Can I just make an if statement and code something like, if accepted run the Google Analytic code which looks something like this:

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-CYZ7731P2S"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-CYZ7731P2S');
</script>

Can someone please let me know how to connect this code with my cookie banner?

Thanks a lot for help!! :slight_smile: