Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ndeblauw's avatar

Alpine - set different x-data value based on screen size

Hi all, I'm working on a list view with filters. On a mobile, the filters should come on top and are hidden by default. On large screens, the filters will show in a left sidebar. For hiding/showing the filters, I plan to use some simple Alpine.js

My main question is, when initializing the component, how do I make the initial value of show (in x-data) conditional of the screen size? That is, false when on mobile, true on any screen larger than a certain size.

<div x-data="{ show: false }">
    <button @click="show = !show">
    Toggle filters
  	</button>
    <div x-show="show">Hello world</div>
</div>
0 likes
2 replies
jaseofspades88's avatar

In Javascript you can use window.innerWidth to get the viewport width. You could therefore assign the value of window.innerWidth > 500 to that of show. Change the width you would like from 500 to the desired width.

1 like
ndeblauw's avatar

Thanks @jaseofspades88. It's indeed quite simple from there.

For anyone looking for the full solution: the code below hides the filters on small screens and shows it on screens from md (768 px) onwards

<div x-data="{ show: false }" x-init="show=window.innerWidth > 768">
    <button @click="show = !show">
    Toggle filters
  	</button>
    <div x-show="show">Hello world</div>
</div>
2 likes

Please or to participate in this conversation.