I’m trying to hide multiple elements inside the DOM by changing shared state when window is resized.
JavaScript
x
6
1
<body class="font-body relative" x-data="{hideOnMobile:false}">
2
<section class="mt-5" :class={'section' : !hideOnMobile , 'hidden' : hideOnMobile}">
3
4
</section>
5
</body>
6
And when i try to
JavaScript
1
8
1
window.onresize = function (event) {
2
let data = document.querySelector('[x-data]');
3
4
if (window.innerWidth > 639) {
5
return data.__x.$data.hideOnMobile = true;
6
}
7
};
8
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.
JavaScript
1
10
10
1
<body
2
class="font-body relative"
3
x-data="{hideOnMobile:false}"
4
@resize.window="hideOnMobile = window.innerWidth > 639"
5
>
6
<section class="mt-5" :class={'section' : !hideOnMobile , 'hidden' : hideOnMobile}">
7
8
</section>
9
</body>
10