3

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?

3 Answers3

7

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>
Hugo
  • 3,500
  • 1
  • 14
  • 28
0

You have no space before x-data attribute. Try to change this line:

<body class="font-body relative"x-data="{hideOnMobile:false}">

to this:

<body class="font-body relative" x-data="{hideOnMobile:false}">

Maksym Bezruchko
  • 1,223
  • 6
  • 23
0

Looks like this is used as an example in the AlpineJS readme. Check this out:

.window modifier Example:

<div x-on:resize.window="isOpen = window.outerWidth > 768 ? false : open"></div>

Adding .window to an event listener will install the listener on the global window object instead of the DOM node on which it is declared. This is useful for when you want to modify component state when something changes with the window, like the resize event. In this example, when the window grows larger than 768 pixels wide, we will close the modal/dropdown, otherwise maintain the same state.