Attempting to tackle a simple task using Alpine JS and the standard JS function setInterval. The goal is to create an image selector where images switch every second (1000ms).
Here's what I have so far:
<div x-data="imgFunc()">
<h1 class="text-xl py-3">Choosing the picture</h1>
<div class="w-1/2">
<img x-show = "img === 'img1'" src="{{ asset('images/training/img1.jpg') }}" alt="Main Image">
<img x-show = "img === 'img2'" src="{{ asset('images/training/img2.jpg') }}" alt="Main Image">
<img x-show = "img === 'img3'" src="{{ asset('images/training/img3.jpg') }}" alt="Main Image">
</div>
<div>
<ul class="flex">
<li class="w-1/6 p-3" :class="{ 'border' : img==='img1' }"><img src=" {{ asset('images/training/img1.jpg') }} " alt="image1" @click = "startImg"></li>
<li class="w-1/6 p-3" :class="{ 'border' : img==='img2' }"><img src=" {{ asset('images/training/img2.jpg') }} " alt="image2" @click = "img='img2'"></li>
<li class="w-1/6 p-3" :class="{ 'border' : img==='img3' }"><img src=" {{ asset('images/training/img3.jpg') }} " alt="image3" @click = "img='img3'"></li>
</ul>
</div>
</div>
<script>
function imgFunc(){
var i = 1;
var img ='img'+i;
return {
i,
img,
startImg(){
var myvar = window.setInterval(function(){
this.img = 'img'+this.i;
if(this.i<3){
this.i++;
}else{
this.i=1;
}
}, 1000);
},
changeImg() {
this.img = 'img'+this.i;
if(this.i<3){
this.i++;
}else{
this.i=1;
}
}
}
}
</script>
When clicking on image#1 in the list, the images should begin changing, but it doesn't happen. Why?
I also attempted passing the function name changeImg() in the @click event, and that worked perfectly, with images changing sequentially upon each click.
I also tried passing the function name changeImg() to setInterval() like this:
startImg(){
var myvar = window.setInterval(this.changeImg, 1000);
},
Or like this:
startImg(){
var myvar = window.setInterval(changeImg, 1000);
},
I experimented with changing "this" to "self"
<script>
function imgFunc(){
var i = 1;
var img ='img'+i;
var self=this;
return {
i,
img,
startImg(){
var myvar = window.setInterval(function(){
self.img = 'img'+self.i;
if(self.i<3){
self.i++;
}else{
self.i=1;
}
}, 1000);
},
changeImg() {
this.img = 'img'+this.i;
if(this.i<3){
this.i++;
}else{
this.i=1;
}
}
}
}
</script>
However, nothing seems to work as intended.