Using Javascript Variable In Different Parts Of Liquid Code

- 1 answer

I'm a total noob ... trying to modify the code in my shopify store.

I need to use a javascript variable in a function to display delivery date.

How can I pass the variable between different javascript codes in the liquid file?

                   {% if shippingtype == 'long' %}         

            <script> var shippingtime = 'long'; </script>

            {% else %}

             <script>  var shippingtime = 'short';   </script>

            {% endif %}


alert(shippingtime); //and do other stuff with variable



I'm afraid it does not work that way. You could do it like you try above, but won't be a clean way of doing it. Instead set your value somewhere in the document where you can read it from, like in an input element.

<input type="hidden" name="shippingtime" value="{{ shippingtime }}"/>   

Then in JavaScript check the value of that input element and handle accordingly.

// Select the input.
const input = document.querySelector('input[name="shippingtime"]');

// Get the value of the input.
const { value } = input;

Whenever you navigate the page you reload everything, including all JS. But you can store variables with the Web Storage API. Either store them in a session with sessionStorage (stored until browser is closed) or indefinitely with localStorage. For this example I'll use the sessionStorage.

// Stores the value.
sessionStorage.setItem('shippingtime', value);

On another page you can check if the storage has an item called shippingtime.

const shippingTime = sessionStorage.getItem('shippingtime');
if (shippingTime !== null) {
  // Use the shippintTime value here.

Hope this helps you out. If you have any questions or I have been unclear, please let me know.