Search code examples
javascriptalpine-linux

How to refresh state in Alpine.js?


Hi guys i am trying to hide my mobile menu when the window is resized above it breakpoint. I have implemented the Alpine.js and it seems to work fine but however when i try to access its x-data to set the boolean to false which should hide, it just doesn't do anything.

<body x-data="{ open: false, navbar: false, resDrop: false }">
  <div class="md:hidden" :class="{'block': navbar, 'hidden': !navbar}">
    <div><span></span></div>
    ...
  </div>
</body>

And when i try to

window.onresize = function (event) {
    let data = document.querySelector('[x-data]');
      
    if (window.innerWidth > 768) {
        return data.__x.getUnobservedData().navbar = false;
    }
};

to return the navbar to its initial close state it just doesn't work. Any way i can achieve this?


Solution

  • Switched to this, now its working perfectly.

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