简体   繁体   中英

Javascript parse error - Google Tag Manager

I have tried to create a custom JavaScript GTM variable after reading a tutorial.

But I just get the message that I have a parse error.

Error at line 43, character 5: Parse error. ')' expected

Not sure what's wrong here. Any ideas? thanks.

function countdown(endDate) {
  var days, hours, minutes, seconds;

  endDate = new Date(endDate).getTime();

  if (isNaN(endDate)) {
    return;
  }

  setInterval(calculate, 1000);

  function calculate() {
    var startDate = new Date();
    startDate = startDate.getTime();

    var timeRemaining = parseInt((endDate - startDate) / 1000);

    if (timeRemaining >= 0) {
      days = parseInt(timeRemaining / 86400);
      timeRemaining = (timeRemaining % 86400);

      hours = parseInt(timeRemaining / 3600);
      timeRemaining = (timeRemaining % 3600);

      minutes = parseInt(timeRemaining / 60);
      timeRemaining = (timeRemaining % 60);

      seconds = parseInt(timeRemaining);

      document.getElementById("days").innerHTML = parseInt(days, 10);
      document.getElementById("hours").innerHTML = ("0" + hours).slice(-2);
      document.getElementById("minutes").innerHTML = ("0" + minutes).slice(-2);
      document.getElementById("seconds").innerHTML = ("0" + seconds).slice(-2);
    } else {
      return;
    }
  }
}

(function () { 
  countdown('09/06/2019 12:00:00 AM'); 
}());

The syntax of a Custom Javascript variable in GTM is the following:

 function() {
   //your code
   return //your result;
 }

This is the reason, why you get an error message, when you try to save your code.

So you need to include only the core functionality, you want to achieve here. However, this type of variable should be used primarily to calculate and return a value, and not to manipulate the DOM.

What you need, is a Custom HTML tag, where the script should be included within a script tag:

<script>
function countdown(endDate) {
  //your countdown function
}

(function () { 
  countdown('09/06/2019 12:00:00 AM'); 
}());
</script>

You will also need a trigger, which launches this tag upon page load. Possibly, only after DOM or on Window Loaded, so that all elements are available, when your script runs.

Also please note, that countdown will be created in the global namespace, so you need to take care not to overwrite an other countdown function, or have it overwritten.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM