Skip to content
Advertisement

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?

Advertisement

Answer

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>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement