Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change shared state in Alpine.js?

I'm trying to hide multiple elements inside the DOM by changing shared state when window is resized.

<body class="font-body relative" x-data="{hideOnMobile:false}">
 <section class="mt-5" :class={'section' : !hideOnMobile , 'hidden' : hideOnMobile}">
   ...
  </section>
</body>

And when i try to

window.onresize = function (event) {
   let data = document.querySelector('[x-data]');
         
       if (window.innerWidth > 639) {
           return data.__x.$data.hideOnMobile = true;
       }
    };

It should change the state ** hideOnMobile** to true but it doesn't somehow any idea?

like image 691
Umedzhon Izbasarov Avatar asked Nov 01 '25 03:11

Umedzhon Izbasarov


1 Answers

Have you tried using @resize.window? (ie. adding the resize listener using Alpine.js) it should make your code simpler than using window.onresize + trying to update Alpine.js __x.$data internal.

<body
  class="font-body relative"
  x-data="{hideOnMobile:false}"
  @resize.window="hideOnMobile = window.innerWidth > 639"
>
 <section class="mt-5" :class={'section' : !hideOnMobile , 'hidden' : hideOnMobile}">
   ...
  </section>
</body>
like image 158
Hugo Avatar answered Nov 03 '25 17:11

Hugo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!