Home > Software design >  Javascript Next Day Delivery Timer
Javascript Next Day Delivery Timer

Time:12-10

On our site, we would like to display

"Want it by Thursday 8th December? Order within 4 hrs 55 mins

At the moment it says: "NEXT DAY UK DELIVERY, order within 4 hrs 55 mins", which is confusing.

How do we generate the next day in script and how do we skip Saturdays and Sundays? The delivery cutoff is 2pm Monday-Friday. The one on this site works well: https://www.yumi.com/

Here is the script we currently have:

function getTimeLeft() {
  var now = moment();
  var deadline = now.clone().hour(14).minute(0).second(0);
  if (now.isAfter(deadline)) {
    var tomorrow = moment(new Date()).add(1, 'days').hour(14).minute(0).second(0);
    //alert(tomorrow);
   // console.log(tomorrow.diff(now, "hours")   ' hrs, '   (tomorrow.diff(now, "minutes") % 60)   ' mins');
    // Display the result in the element with id="demo"
  document.getElementById("demo3").innerHTML = "<b>NEXT DAY UK DELIVERY</b>, order within<b>"   " "  tomorrow.diff(now, "hours")   ' hrs '    (tomorrow.diff(now, "minutes") % 60)   ' mins'   "</b> ";

  } else {
//     console.log(deadline.diff(now, "hours")   ' hrs, '   (deadline.diff(now, "minutes") % 60)   ' mins');
     document.getElementById("demo3").innerHTML = "<b>NEXT DAY UK DELIVERY</b>, order within<b>"   " "  deadline.diff(now, "hours")   ' hrs '   (deadline.diff(now, "minutes") % 60)   ' mins'   " </b>";
  }
} 

getTimeLeft();
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>

<div id="demo3"></div>

This was built by developers.

CodePudding user response:

Try this code:

function returnDeliveryDate() {
  switch (moment().clone().add(1, 'days').day()) {
    case 6:
      return moment().clone().add(3, 'days');
    case 0:
      return moment().clone().add(2, 'days');
    default:
      return moment().clone().add(1, 'days');
  }
}

function getTimeLeft() {
  var now = moment();
  var deadline = now.clone().hour(14).minute(0).second(0);
  var expectedDeliveryDate = 
  returnDeliveryDate().hour(14).minute(0).second(0);
  
if (now.isAfter(deadline)) {
    document.getElementById('demo3').innerHTML =
    'delivery in,'  
    expectedDeliveryDate.format()  
    'order within'  
    ' '  
    expectedDeliveryDate.diff(now, 'hours')  
   ' hrs '  
   (expectedDeliveryDate.diff(now, 'minutes') % 60)  
   ' mins';
   } else {
   document.getElementById('demo3').innerHTML = 'delivery in,'  
   deadline.format()  
   'order within'  
   ' '  
   deadline.diff(now, 'hours')  
  ' hrs '  
  (deadline.diff(now, 'minutes') % 60)  
  ' mins';;
}
   }
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>

<div id="demo3"></div>

I basically left your code as is except of the tomorrow date part. All you have to do now is to format the date as you need and maybe change the message text.

Hope this is what you wanted.

CodePudding user response:

Sorry I'm struggling with this. This is what our product-template file looks like now

<div  itemscope itemtype="http://schema.org/Product" id="ProductSection-{{ section.id }}" data-section-id="{{ section.id }}" data-section-type="product" data-enable-history-state="true" data-ajax="{{ section.settings.enable_ajax }}" data-stock="{{ section.settings.stock_enable }}">
  {% assign product_image_size = '680x680' %}

  <meta itemprop="name" content="{{ product.title }}">
  <meta itemprop="url" content="{{ shop.url }}{{ product.url }}">
  <meta itemprop="image" content="{{ product.featured_image.src | img_url: '600x600' }}">
  {%- if settings.product_vendor_enable -%} 
    <meta itemprop="brand" content="{{ product.vendor }}">
  {%- endif -%}

  {% comment %}
    Get first variant, or deep linked one
  {% endcomment %}
  {% assign current_variant = product.selected_or_first_available_variant %}
  <div class='sv_breadcrubs'>
    {% include 'breadcrumbs' %}
    </div>
    <div >
   <div >
      <div >
        <div >
          <div  id="ProductPhoto">
            {% assign featured_image = current_variant.featured_image | default: product.featured_image %}
            <a href="{{ featured_image | img_url: '1024x1024' }}"  id="ProductPhotoLink-{{ section.id }}">
              <img src="{{ featured_image | img_url: product_image_size }}" alt="{{ featured_image.alt | escape }}" id="ProductPhotoImg-{{ section.id }}">
            </a>
          </div>
        </div>
        {% if product.images.size > 1 %}
          <div >
            <div  id="ProductThumbs-{{ section.id }}">
              {% for image in product.images %}
                <div >
                  <a href="{{ image.src | img_url: product_image_size }}" data-zoom="{{ image.src | img_url: '1024x1024' }}" >
                    <img src="{{ image.src | img_url: '160x160' }}" alt="{{ image.alt | escape }}">
                  </a>
                </div>
              {% endfor %}
            </div>
          </div>
        {% endif %}
        {% if product.images.size > 2 %}
          {% comment %}
            Add SVG icon snippets to an object for custom slider arrows
          {% endcomment %}
          <script>
            {% capture arrow_left %}{% include 'icon-arrow-left' %}{% endcapture %}
            {% capture arrow_right %}{% include 'icon-arrow-right' %}{% endcapture %}
            {% capture arrow_up %}{% include 'icon-arrow-up' %}{% endcapture %}
            {% capture arrow_down %}{% include 'icon-arrow-down' %}{% endcapture %}
            var sliderArrows = {
              left: {{ arrow_left | json }},
              right: {{ arrow_right | json }},
              up: {{ arrow_up | json }},
              down: {{ arrow_down | json }}
            }
          </script>
        {% endif %}
      </div>
    </div>
<!--<div id="desktop-images" ></div>
 <script>
  var p = {{ product | json }};
  //console.log(p.featured_image);
  var array_images = p.images;
  $.each(array_images , function(index, val) { 
  //console.log(index, val)
$("#desktop-images").append("<img src=" val " width='350px' height='350px' class='pro-img'/>");
   
});
</script> -->
    <div  itemprop="offers" itemscope itemtype="http://schema.org/Offer">
      <div >
        <meta itemprop="priceCurrency" content="{{ shop.currency }}">
     
        <link itemprop="availability" href="http://schema.org/{% if product.available %}InStock{% else %}OutOfStock{% endif %}">
      
       
        <div >
          {% if settings.product_vendor_enable %}
            <p >{{ product.vendor }}</p>
          {% endif %}

          <h1 itemprop="name" >{{ product.title }}</h1>
          
<span  data-id="{{ product.id }}" data-product-title="{{ product.title | escape }}" data-product-type="{{ product.type }}" style="display: block;" onclick="$('#gift_tab').click();$('#gift_tab').addClass('block');"></span>
          
                
                 
          <ul >
            <li id="ProductSaleTag-{{ section.id }}" >
              <div >
                {{ 'products.product.on_sale' | t }}
              </div>
            </li>
             {% if product.compare_at_price_max > product.price %}
              <li>
                <span >{{ 'products.product.regular_price' | t }}</span>
                <s id="ComparePrice-{{ section.id }}" >
                  {{ current_variant.compare_at_price | money }}
                </s>
              </li>
            {% endif %}
            <li>
              {% unless product.compare_at_price_max > product.price %}
                <span >{{ 'products.product.regular_price' | t }}</span>
              {% endunless %}
              <span id="ProductPrice-{{ section.id }}"  itemprop="price" content="{{ current_variant.price | divided_by: 100.00 }}">
                {{ current_variant.price | money }}
                
              </span>
             </li>             
             <!-- Swym Wishlist Plus EPI Button-->
  <button data-with-epi="true"  data-swaction="addToWishlist" data-product-id="{{product.id | json}}" data-variant-id="{{product.variants[0].id}}" data-product-url="{{ shop.url }}{{ product.url }}"></button>
  <!-- Swym Wishlist Plus EPI Button-->


            <!-- <p >  {{product.vendor}} </p>-->
           
          {% for t in product.tags %}
          {% if t contains 'MIX & MATCH' %}
            <li><a  href="https://martinschocolatier.co.uk/collections/mix-and-match">MIX & MATCH - 3 FOR 2</a></li>
          {% endif %}
          {% endfor %}
           
            {% if section.settings.stock_enable %}
              <li>
                <span id="ProductStock-{{ section.id }}" >
                  {% if current_variant.inventory_management %}
                    {% if current_variant.inventory_quantity < 10 and current_variant.inventory_quantity > 0 %}
                      {% assign qty = current_variant.inventory_quantity %}
                      {{ 'products.product.stock_available' | t: count: qty }}
                    {% elsif current_variant.inventory_quantity == 0 or current_variant.inventory_quantity < 0 and current_variant.incoming %}
                      {% if current_variant.available %}
                        {% assign date = current_variant.next_incoming_date | date: "%B %-d, %Y" %}
                        {{ 'products.product.will_not_ship_until' | t: date: date  }}
                      {% else %}
                        {% assign date = current_variant.next_incoming_date | date: "%B %-d, %Y" %}
                        {{ 'products.product.will_be_in_stock_after' | t: date: date  }}
                      {% endif %}
                    {% endif %}
                  {% endif %}
                </span>
              </li>
            {% endif %}
    
          </ul>
                  
        </div>
       
         <div class='cart_wish'>
           <div class='choco_cart_form_custom'>
        <form action="/cart/add" method="post" enctype="multipart/form-data"  id="AddToCartForm">

          {% unless product.options.size == 1 and product.variants[0].title == 'Default Title' %}
            {% for option in product.options_with_values %}
              <div >
                <label {% if option.name == 'default' %} {% endif %}for="SingleOptionSelector-{{ section.id }}-{{ forloop.index0 }}">{{ option.name }}</label>
                <select 
                  id="SingleOptionSelector-{{ forloop.index0 }}"
                  data-name="{{ option.name }}"
                  data-index="option{{ forloop.index }}">
                  {% for value in option.values %}
                    <option value="{{ value | escape }}"{% if option.selected_value == value %} selected="selected"{% endif %}>{{ value }}</option>
                  {% endfor %}
                </select>
              </div>
            {% endfor %}
          {% endunless %}
           <div style=" display: flex; flex-wrap: wrap; ">
          <select name="id" id="ProductSelect-{{ section.id }}" >
            {% for variant in product.variants %}
              <option {% if variant == current_variant %} selected="selected" {% endif %} data-sku="{{ variant.sku }}" value="{{ variant.id }}" {% unless variant.available %} disabled="disabled" {% endunless %}>
                {% if variant.available %}
                  {{ variant.title }} - {{ variant.price | money_with_currency }}
                {% else %}
                  {{ variant.title }} - {{ 'products.product.sold_out' | t }}
                {% endif %}
              </option>
            {% endfor %}
          </select>

            <div >
                <div  style="height: 53px;">
                  <label for="Quantity">{{ 'products.product.quantity' | t }}</label>
                  <input type="number" id="Quantity" name="quantity" value="1" min="1" >
                </div>
{%  if product.tags contains 'vegan' %}
              <div  style="width: 100%;" data-block-id="05d1c5c5-0cc9-4e22-a15f-fa3a2fc29425"></div>{% endif %}
            </div>
  
 {% unless product.content contains 'zakeke-design-tag' %}

{% endunless %}     
 {% if product.tags contains 'zakeke-product' or product.content contains 'zakeke-product-tag' %}
   <button id="zakeke-product-button" style="width: 100%;" >
 <span>Personalise</span>
 </button>
 <input name="zakeke-product-id" type="hidden" value="{{ product.id }}">
 <script>
  (function () {
    function findAncestor (el, sel) {
      while ((el = el.parentElement) && !((el.matches || el.matchesSelector).call(el,sel)));
      return el;
    }

    var btn = document.querySelector('#zakeke-product-button');
    btn.addEventListener('click', function (event) {
      event.preventDefault();
      event.stopPropagation();
      var form = findAncestor(btn, 'form');
      if (!form || !form.reportValidity()) {
        return;
      }
      var pid = form.querySelector('input[name="zakeke-product-id"]').value;
      
      var originalAction = form.action;
      form.action = (window.zakekeUrl || '/apps/zakeke')   '?pid='   pid;

      window.onpageshow = function(event) {
          if (event.persisted) {
              form.action = originalAction;
          }
      };
      form.submit();
    });
  })();
  </script>
 {% endif %}       

        
          <div  style=" padding-left: 0px !important; padding-right: 0px !important; flex: 100%;margin-bottom: 0; margin-top: 0; padding-top: 10px; padding-bottom: 10px">
            <button type="submit"
              name="add"
              id="AddToCart-{{ section.id }}"
              
              {% unless current_variant.available %}disabled="disabled"{% endunless %}>
              <span id="AddToCartText-{{ section.id }}">
                {% unless current_variant.available %}
                  {{ 'products.product.sold_out' | t }}
                {% else %}

                  {{ 'products.product.add_to_cart' | t }}

         {% endunless %}       
              </span>
            </button>
          </div></div>
                </form>
    <div style="border:1px solid #ccc;margin-bottom: 10px;padding-top: 10px;text-align:center"> 
                       <div style="display: inline-block; " >
                    <label style="display:inline; float:none" for="effectiveAppsEGWATC">
                      <input style="-webkit-appearance: checkbox; float:none; vertical-align: middle;" type="checkbox" id="effectiveAppsEGWATC" name="effectiveAppsEGWATC" onchange="window.effectiveAppsEGWModal.open();"> 
                      <span><strong style="text-transform: initial; font-size: 14px; color: black;"><img src = "https://cdn.shopify.com/s/files/1/0566/7389/4570/files/giftbox.png?v=1666338627"width="50" height="50" style="vertical-align:middle">Add a PERSONAL message and GIFT WRAP to this order from £2.00
                      
</strong></span></label><br /><br /> </div></div>
<!--         <div id="ping-app"></div> -->


 <!--<span ><img  src="https://cdn.shopify.com/s/files/1/0566/7389/4570/files/2021-08-19_3.png?v=1629369718">Make 3 payments of
          <span id="ProductPriceklarna-{{ section.id }}"  itemprop="price" content="{{ current_variant.price | divided_by: 100.00 }}">
                {{ current_variant.price | money }}
              </span>.No fees. <a  href="">Learn more</a></span>-->
        




<!-- Placement v2 -->
<!--<klarna-placement
  data-key="top-strip-promotion-auto-size"
  data-locale="en-GB"
></klarna-placement> -->
<!-- end Placement -->

            <!-- Placement afterpay -->
<!--div style="border:1px solid #ccc;margin-bottom: 10px;text-align:center; padding-left: 20px; padding-right:20px";>
<afterpay-placement 
    data-locale="en_GB"
    data-currency="GBP" 
    data-amount="400"
  data-logtype ="lockup">-->
  
    </afterpay-placement></div>
  
    <!-- end Placement -->
       

<!-- Placement v2 -->
<klarna-placement
data-key="credit-promotion-auto-size" 
data-locale="en-GB"
data-purchase-amount="{{ current_variant.price }}"> 
</klarna-placement> 
<!-- end Placement -->
  

   <div class='wishlist_div'>
     <div id="drop-hint-div"><div id="dropahint_wrapper"></div>
</div>
        {% include 'wishlist-product' %}
           
        </div> 
        {{ 'wish-list.js' | asset_url | script_tag }}
        <div >
 
          <li  style='float:right;padding:3px;'><!--<span><img src="https://cdn.shopify.com/s/files/1/0566/7389/4570/files/2021-08-19_1.png?v=1629369689"  title="My image" /></span>
         <!-- <span class='order_bytime'>Order within <label>--><!--<div id="pro_timer"> </div> <!--</label> for <label>UK NEXT DAY DELIVERY</label>
              </span>-->
            
           
          </li>
        </div>
        <div  style="border:1px solid #ccc;margin-top:74px">  <p id="demo3"></p> </div>

        <div id="pro_timer"> </div>
        
        <div  itemprop="description">
          <div class='desc_hd'>Detailed Info <span id='desc_tab'>-</span></div>
          <div class='dv_choco_desc'>
          {{ product.description }}
          </div>
      <div>
                    

             

{% assign count = product.metafields.custom.ingredients | size %}
<script>console.log('anctest ','{{ count }}');</script>

 {% if count > 1 %} 
<div class='ingredients-new'>Ingredients<span id='ingredients_tab'> </span></div>
<div class='ingredients dv_choco_desc'>Ingredients<span id='ingredients_tab'> </span></div> <div class='dv_choco_ingredients'> 
   {{ product.metafields.custom.ingredients }} </div> {% endif %}
          </div>
<div>

          <div class='gift-wrap-new'>Product Reviews<span id='gift_tab'> </span></div>
          <div class='dv_choco_gift'>
    <!--Stamped - Begin Main Widget -->
<div 
id="stamped-main-widget"   
data-product-id="{{ product.id }}"   
data-name="{{ product.title | escape }}"   
data-url="{{ shop.url }}{{ product.url }}"   
data-image-url="{{ product.featured_image | product_img_url: "large" |replace: '?', '?' | replace: '&','&'}}" 
data-description="{{ product.description | escape }}"   
data-product-sku="{{product.handle}}"
data-product-title="{{product.title}}" 
data-product-type="{{product.type}}">   
{{product.metafields.stamped.reviews}}   
</div>
<!-- Stamped - End Main Widget -->
          </div></div></div></div>
        <!--<div class='gift-wrap' style="display: block !important;">Gift Wrapping<span id='gift_tab'></span>
                 
             </div>
        
          <div class='dv_choco_gift'>
          <div id="shopify-product-gift" class='choco_gift' data-id="{{product.id}}">{{ product.gift }}</div>
          </div>--->
{% comment %}
        {% if section.settings.social_sharing_products %}
          {% include 'social-sharing', share_title: product.title, share_permalink: product.url, share_image: product %}
        {% endif %}
        {% endcomment %}
      </div>
    </div>
  </div> 
</div>

<style>
  span#timer-mins:after {content: "for NEXT Day DELIVERY";}

#demo3:before {
content: url(https://cdn.shopify.com/s/files/1/0566/7389/4570/files/2021-08-19_1.png?v=1629369689);
    top: 3px;
    position: relative;
    right: 3px;

}
  span#timer-secs {
    display: none;
}
  .main-timer {
    top: 5px;
    position: relative;
}
  div#pro_timer {
    
    width: 100%;
   
}
.timer-content {
    border: 1px solid #ccc;
    width: 100%;
    /* text-align: center; */
    top: 12px;
    position: relative;
    height: 40px;
    justify-content: center;
}
  i.spr-icon.spr-icon-star {
    color: orange;
}
  span.spr-starrating.spr-summary-starrating {
    display: none;
}
  h2.spr-header-title {
    display: none;
}
  .dv_choco_gift {
    padding: 15px 15px 15px 15px;
    border-top: #cecece solid 1px;
}
  a.mix-pro {
    color: black;
}
</style>
<script>


</script>
<script> 
   $(".dv_choco_ingredients").hide();
    $(".dv_choco_gift").hide();
    $(".dv_choco_review").hide();
    $(".dv_choco_shipping").hide();
$("#desc_tab").click(function(){
    if($(this).html() == "-"){
        $(this).html(" ");
    }
    else{
        $(this).html("-");
    }
    $(".dv_choco_desc").slideToggle();
});
  
  $("#review_tab").click(function(){
    if($(this).html() == "-"){
        $(this).html(" ");
    }
    else{
        $(this).html("-");
    }
    $(".dv_choco_review").slideToggle();
});
   $("#shipping_tab").click(function(){
    if($(this).html() == "-"){
        $(this).html(" ");
    }
    else{
        $(this).html("-");
    }
    $(".dv_choco_shipping").slideToggle();
});
   $("#ingredients_tab").click(function(){
    if($(this).html() == "-"){
        $(this).html(" ");
    }
    else{
        $(this).html("-");
    }
    $(".dv_choco_ingredients").slideToggle();
});
   $("#gift_tab").click(function(){
    if($(this).html() == "-"){
        $(this).html(" ");
    }
    else{
        $(this).html("-");
    }
    $(".dv_choco_gift").slideToggle();
});
  
  
</script>

<script>
   $( document ).ready(function() {
    var len = $(".product-single #desktop-images .pro-img").length;
    if(len == 1)
    {
    $(".product-single #desktop-images .pro-img").css({"width":"100%","height":"50%"});
    }
  });
</script>

<script>
function returnDeliveryDate() {
  switch (moment().clone().add(1, 'days').day()) {
    case 6:
      return moment().clone().add(3, 'days');
    case 0:
      return moment().clone().add(2, 'days');
    default:
      return moment().clone().add(1, 'days');
  }
}

function getTimeLeft() {
  var now = moment();
  var deadline = now.clone().hour(14).minute(0).second(0);
  var expectedDeliveryDate = 
  returnDeliveryDate().hour(14).minute(0).second(0);
  
if (now.isAfter(deadline)) {
    document.getElementById('demo3').innerHTML =
    'delivery in,'  
    expectedDeliveryDate.format()  
    'order within'  
    ' '  
    expectedDeliveryDate.diff(now, 'hours')  
   ' hrs '  
   (expectedDeliveryDate.diff(now, 'minutes') % 60)  
   ' mins';
   } else {
   document.getElementById('demo3').innerHTML = 'delivery in,'  
   deadline.format()  
   'order within'  
   ' '  
   deadline.diff(now, 'hours')  
  ' hrs '  
  (deadline.diff(now, 'minutes') % 60)  
  ' mins';;
}
   }
 
</script>

{% unless product == empty %}
  <script type="application/json" id="ProductJson-{{ section.id }}">
    {{ product | json }}
  </script>
  {% if section.settings.stock_enable %}
    <script type="application/json" id="VariantJson-{{ section.id }}">
      [
        {% for variant in product.variants %}
          {
             "incoming": {{ variant.incoming | default: false | json }},
             "next_incoming_date": {{ variant.next_incoming_date | date: format: 'month_day_year' | json }}
          }{% unless forloop.last %},{% endunless %}
        {% endfor %}
      ]
    </script>
  {% endif %}
{% endunless %}

{% schema %}
  {
    "name": "Product pages",
    "settings": [
      {
        "type": "checkbox",
        "id": "enable_ajax",
        "label": "Stay on current page when item is added to cart",
        "default": true
      },
      {
        "type": "checkbox",
        "id": "stock_enable",
        "label": "Show stock when less than 10 products available",
        "default": false
      },
      {
        "type": "checkbox",
        "id": "social_sharing_products",
        "label": "Enable product sharing",
        "default": true
      }
    ]
  }
{% endschema %}
  • Related