Multiple countdown using metafield values

Joiakim
New Member
7 0 0

Dear community,

I am trying to build a specific feature for my products. The goal is to display each available variant of the product in a row . In each row I need to show a countdown timer above the "add to cart" button. 

Since I am importing products directly from a third party supplier, I am using metafields to specify the ending date of the timer. So far I was able to sort out the countdown code in javascript which should display the remaining time to purchase in days, hours, minutes and seconds. Using the {% if %} tag, the countdown should be displayed only for variant where a metafield is specified. 

The problem as you can see is that the countdown is identical for all variants even when dates are specified for other variants. Could you please help me understand what I missed so that the countdown works for each variant's metafield? 

Joiakim_0-1635974220206.png

Here is my code : 

 

 

{% if variant.metafields.custom_fields.launch  %}

{% assign launch_date = variant.metafields.custom_fields.launch.value %}


  <div class="countdown-timer">
    <span class="time days"></span>
    <span class="separator">days</span>
    <span class="time hours"></span>
    <span class="separator">hours</span>
    <span class="time minutes"></span>
    <span class="separator">minutes</span>
    <span class="time seconds"></span>
    <span class="separator">seconds</span>    
  </div>

<script type="text/javascript">
 const second = 1000,
      minute = second * 60,
      hour = minute * 60,
      day = hour * 24,
      year = day * 365;

var countDown = new Date("{{ launch_date }}").getTime()
x = setInterval(function() {
  var now = new Date().getTime();
  var distance = countDown - now;
  
  
   $('.days').each(function() {
    $(this).text(("0" + Math.floor((distance % (year)) / (day))).slice(-2));
  })

  $('.hours').each(function() {
    $(this).text(("0" + Math.floor((distance % (day)) / (hour))).slice(-2));
  })

  $('.minutes').each(function() {
    $(this).text(("0" + Math.floor((distance % (hour)) / (minute))).slice(-2));
  })

  $('.seconds').each(function() {
    $(this).text(("0" + Math.floor((distance % (minute)) / second)).slice(-2));
  })

 if (distance < 0) { 
           clearInterval(x); 
          $(".countdown-timer").hide(1); 
       } 
  
  }, second)
</script>

{% endif %}

 

 

 

Replies 0 (0)