How can I assign a variable based on window width in Liquid and Javascript?

Topic summary

A developer needs to assign a Liquid variable dynamically based on browser window width, with different division values (3.0 or 4.0) depending on whether the viewport is above or below 991px.

Initial Approach & Problem:

  • Attempted using JavaScript with window.innerWidth checks and document.write() to inject Liquid {% assign %} statements
  • While console.log() works and detects window resizing, the Liquid variable remains unassigned
  • The variable displays nothing when rendered with {{ value }}

Key Issue:
Liquid is a server-side templating language that executes before the page loads, while JavaScript runs client-side in the browser. This timing mismatch prevents JavaScript from modifying Liquid variables after page generation.

Proposed Solution:
One response suggests starting with an initial Liquid assignment and likely using JavaScript to handle the dynamic calculation client-side, though the complete solution code appears corrupted in the thread.

Status: The discussion remains open with an incomplete answer.

Summarized with AI on November 12. AI used: claude-sonnet-4-5-20250929.

I need to value a variable based on the width of the window.

The line to value is this

{% assign value = column_number | divided_by: value %}

based on window it is greater than 991 the value variable must take on

4.0 or 3.0

I tried with javascript

<script> if(window.innerWidth < 991 ) {
console.log(3);
document.write("{% assign value = column_number | divided_by: 3.0 %}");
}
else
{
console.log(4);
document.write("{% assign value = column_number | divided_by: 4.0 %}");
}
console.log(window.innerWidth);
</script>
valore {{ value  }}

but nothing. the value {{ value }} is not valued

If I tighten or widen the window the change is noticed and the console log also works, but the variable is not displayed in liquid

You can try the following code:

{% assign initial_value = column_number | divided_by: 4.0 %}

Value: {{ initial_value }}