Drawer Cart: Automatically Clear Datepicker After X Hours

This tutorial explains how to clear the date picker (or any input) automatically after a set number of hours. This ensures that if a customer selects a date but doesn’t check out, they’ll need to reselect a date before proceeding.

The script listens for when a customer selects a date, stores that data in a cookie with a time-to-live (TTL), and clears the input when the TTL expires.

Important Note: This is an advanced tutorial designed for qualified Shopify developers with JavaScript experience. If you’re not working with a developer and need assistance, we can implement this for a flat fee of $100 USD. Payment can be made at: https://shop.gist-apps.com.

Step 1: Duplicate Your Live Theme

Always work on a duplicate of your live theme to prevent unwanted changes from affecting your storefront.

Step 2: Create and Upload the Snippet

  1. In your Shopify admin, go to your theme’s Assets folder.
  2. Create a new JavaScript file called giftship-date-ttl.js.
  3. Copy and paste the code provided below into this file.
(() => {

    const CONFIG = {
        inputName: "attributes[Delivery By]", // Name of the datepicker input
        storageKey: "gs_date_ttl", // Key for the cookie
        ttlMinutes: 1, // Time-to-live for the cookie
        maxRetries: 5, // Maximum retries for DOM querying
        retryInterval: 1000, // Retry interval in milliseconds
    };

    const Utils = {
        /**
         * Get an input element by its name attribute.
         * @param {string} name - The name attribute of the input.
         * @returns {HTMLElement|null} - The input element or null if not found.
         */
        getElementByName: (name) => document.querySelector(`input[name="${name}"]`),

        /**
         * Set a cookie with a specified TTL.
         * @param {string} key - The cookie name.
         * @param {string|boolean} value - The cookie value.
         * @param {number} minutes - TTL in minutes.
         */
        setCookie: (key, value, minutes) => {
            try {
                const expiry = new Date();
                expiry.setTime(expiry.getTime() + minutes * 60 * 1000);
                document.cookie = `${key}=${value}; expires=${expiry.toUTCString()}; path=/`;
            } catch (error) {
                console.error(`Failed to set cookie: ${error}`);
            }
        },

        /**
         * Get the value of a cookie by its key.
         * @param {string} key - The cookie name.
         * @returns {string|null} - The cookie value or null if not found.
         */
        getCookie: (key) => {
            try {
                const cookies = document.cookie.split("; ");
                for (const cookie of cookies) {
                    const [cookieKey, cookieValue] = cookie.split("=");
                    if (cookieKey === key) return cookieValue;
                }
                return null;
            } catch (error) {
                console.error(`Failed to get cookie: ${error}`);
                return null;
            }
        },

        /**
         * Remove a cookie by its key.
         * @param {string} key - The cookie name.
         */
        removeCookie: (key) => {
            try {
                document.cookie = `${key}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
            } catch (error) {
                console.error(`Failed to remove cookie: ${error}`);
            }
        },
    };

    const MODULE = {
        datepickerInput: null, // Cache for the input element

        /**
         * Initialize the module.
         * @param {number} retries - Number of retries for DOM querying.
         */
        init: function (retries = CONFIG.maxRetries) {
            this.datepickerInput = Utils.getElementByName(CONFIG.inputName);

            if (!this.datepickerInput && retries > 0) {
                console.warn(`Datepicker input not found. Retrying... (${retries} retries left)`);
                setTimeout(() => this.init(retries - 1), CONFIG.retryInterval);
                return;
            }

            if (!this.datepickerInput) {
                console.error("Failed to initialize module. Datepicker input not found.");
                return;
            }

            this.cleanEventListeners(); // Ensure no duplicate listeners
            this.observeInputChange();
            this.checkAndClearInput();
        },

        /**
         * Clean up existing event listeners.
         */
        cleanEventListeners: function () {
            if (this.datepickerInput) {
                this.datepickerInput.removeEventListener("change", this.onDateChange.bind(this));
            }
        },

        /**
         * Attach event listener to the datepicker input for the 'change' event.
         */
        observeInputChange: function () {
            if (this.datepickerInput) {
                this.datepickerInput.addEventListener("change", this.onDateChange.bind(this));
                console.log("Event listener attached to datepicker input.");
            }
        },

        /**
         * Handle datepicker input change.
         */
        onDateChange: function () {
            console.log("Datepicker value changed. Setting cookie...");
            Utils.setCookie(CONFIG.storageKey, true, CONFIG.ttlMinutes);
        },

        /**
         * Check if a valid cookie exists and clear the datepicker input if necessary.
         */
        checkAndClearInput: function () {
            const cookieExists = Utils.getCookie(CONFIG.storageKey);
            if (!cookieExists && this.datepickerInput && this.datepickerInput.value) {
                console.log("No valid cookie found. Clearing datepicker input...");
                this.clearInput();
            }
        },

        /**
         * Clear the value of the datepicker input.
         */
        clearInput: function () {
            if (this.datepickerInput) {
                this.datepickerInput.value = "";
                console.log("Datepicker input cleared.");
            }
        },
    };

    // Initialize the module when Giftship events are triggered
    const initializeModuleOnEvent = () => MODULE.init();

    document.addEventListener("giftship.loaded", initializeModuleOnEvent);
    document.addEventListener("giftship.drawer-cart.opened", initializeModuleOnEvent);

})();

Step 3: Customize the Script

Update the following in the script:

  • inputName: Set this to match your date picker input name (e.g. attributes[Delivery By])
  • ttlMinutes: Adjust the number of minutes before the input is cleared. Default is 1 minute for testing.

Step 4: Include the Script in theme.liquid

  1. Open theme.liquid in the theme editor.
  2. Scroll to the bottom of the file, just above the closing </body> tag.
  3. Paste this line:
<script src="{{ 'giftship-date-ttl.js' | asset_url }}"></script>

Step 5: Testing

Open your browser console and go to the Application tab in Chrome.
Under Cookies, find the one labeled gs_date_ttl and delete it.

Can't find the answer in our documentation?
Contact Support