Slide div inside another div effect
Posted
by mariki
on Stack Overflow
See other posts from Stack Overflow
or by mariki
Published on 2010-04-11T09:59:56Z
Indexed on
2010/04/11
10:03 UTC
Read the original article
Hit count: 339
JavaScript
|html
I am trying to create sliding images effect: Online demolink text.
The problem is when you click rapidly and randomly on the buttons and not wait for animation to finish causing unpredicted results and even stopping the functionality to work. (and once it stopped in the middle of 2 images...)
How Can I make it work without bugs?
I know that there are some other tools for that sliding like jquery and other approaches like changing the position attribute and not the scrollLeft attribute.
But I want to do it as it is, with scrollLeft, if it 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>
© Stack Overflow or respective owner