Warm tip: This article is reproduced from stackoverflow.com, please click
javascript liquid shopify

Using javascript variable in different parts of liquid code

发布于 2020-04-21 11:16:04

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 %}


            <script> 

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

</script>
Questioner
Tom humphries
Viewed
35
Emiel Zuurbier 2020-02-06 06:37

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.
  console.log(shippingTime);
}

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