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?
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?
Share Improve this question edited Oct 29, 2020 at 8:14 Umedzhon Izbasarov asked Oct 27, 2020 at 16:09 Umedzhon IzbasarovUmedzhon Izbasarov 731 silver badge9 bronze badges 3- So the logic here states to hide on mobile when the window is larger than 639? Is that correct? – Steve O Commented Nov 24, 2020 at 12:18
-
I'm guessing there's other stuff going on but in this example you could just use the tailwind breakpoint helpers e.g.
<div class="hidden sm:block">Hidden on mobile</div>
– Steve O Commented Nov 24, 2020 at 12:21 - @SteveO yes the logic is correct – Umedzhon Izbasarov Commented Nov 30, 2020 at 15:18
3 Answers
Reset to default 7Have 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>
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}">
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 ponent 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.