'Why does this setinterval work only once? [duplicate]
Ok so, on my website I have three long panorama images on top of each other. I want them all to scoot 100px to the left every second. Here's what I tried:
var panoramas = document.getElementsByClassName("pano");
setInterval(scoot, 1000);
function scoot(){
for (i=0; i < panoramas.length; i++){
panoramas[i].style.left = panoramas[i].style.left - 100;
}
}
But what happens is that they scoot 100px to the left once, and stop. I tried some console.logs in there so I know it's looping, but they won't move more than once.
Solution 1:[1]
panoramas[i].style.left does not read styles from CSS files. It returns a string with unit and expects a string with unit.
var panoramas = document.getElementsByClassName("pano");
setInterval(scoot, 1000);
function scoot() {
for (i = 0; i < panoramas.length; i++) {
panoramas[i].style.left = panoramas[i].style.left.replace(/\d+/, p1 => +p1 - 100);
}
}
.pano {
display: block;
width: 50px;
height: 50px;
background-color: blue;
position: absolute;
}
<div class="pano" style="left: 200px; top: 50px;"></div>
<div class="pano" style="left: 250px; top: 100px;"></div>
<div class="pano" style="left: 300px; top= 150px;"></div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
