Reputation: 70
I want to hide an element with Alpine after X number of seconds. So I need to run a setTimeout() that changes an x-data variable that the element's x-show is bound to.
I'm currently using the script tag with normal JS in, but I can't seem to access the x-data variables from it.
As an example:
<div x-data="showSomething = true">
<script>
setTimeout(() => {
this.showSomething = false;
}, 1500);
</script>
</div>
I get this error whether I use "this." or not:
Uncaught ReferenceError: showSomething is not defined
How can I access the x-data variables from normal JS, or is there a way to go about this in Alpine?
Edit: I solved this by using x-on to listen for the event (and referring to the variables without .this within that function)
Upvotes: 0
Views: 4305
Reputation: 15786
Use x-init
.
<div
x-data="{ showSomething: true }"
x-init="setTimeout(() => { this.showSomething = false; }, 1500)"
>
</div>
Upvotes: 5