I'm trying to create a moving image effect: Demo link text .
The problem is that you quickly and accidentally press buttons and do not wait for the animation to end, which leads to unpredictable results and even stops working. (and as soon as he stopped in the middle of 2 images ...)
How can I make it work without errors?
I know that there are some other tools for sliding like jquery and other approaches like changing the position attribute rather than the scrollLeft attribute. But I want to make it as it is, with scrollLeft, if possible, of course.
The code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
<style type="text/css">
body
{
padding:0px;
margin:0px;
}
#imageContainer
{
width: 500px;
position: relative;
}
#div
{
overflow: hidden;
white-space: nowrap;
}
#div img {
cursor: pointer;
vertical-align: bottom;
width: 500px;
padding:0px;
margin:0px;
display:inline;
}
</style>
<script type="text/javascript">
var scrollIntervalID;
var currentIndex=0;
function Scroll(ind){
var dir = ind ==currentIndex?0:ind<currentIndex?-1:1;
var steps = Math.abs(ind-currentIndex);
scrollIntervalID = setInterval(function(){
var i=(steps*10)-1;
return function(){
if (i <= 0)
clearInterval(scrollIntervalID);
var elm = document.getElementById("div");
elm.scrollLeft +=dir * 50;
i--;
document.getElementById("span").innerHTML=elm.scrollLeft;
}
}(), 15);
currentIndex=ind;
}
</script>
</head>
<body>
<div id="imageContainer">
<div id="div">
<img id="image1" src="Images/pic1.jpg" width="500px"/><img id="image2" src="Images/pic2.jpg" width="500px"/><img id="image3" src="Images/pic3.jpg" width="500px"/><img id="image4" src="Images/pic4.jpg" width="500px"/>
</div>
</div>
<div>
<input type="button" value="1" onclick="Scroll(0);"/>
<input type="button" value="2" onclick="Scroll(1);"/>
<input type="button" value="3" onclick="Scroll(2);"/>
<input type="button" value="4" onclick="Scroll(3);"/>
</div>
<span id="span"></span>
</body>
</html>
source
share