Working on enhancing my jQuery skills by constructing a basic slider with 3 slides. The slider wrapper, with a fixed width of 1400px and a height of 350px serves as the outer container.
Within this wrapper lies an unordered list where its items are floated left to enable them to be displayed in a horizontal arrangement. This entire unordered list is then animated to shift to the left by 1400px, creating the sliding effect. I am currently facing a challenge determining how to smoothly return to the initial slide without any abrupt transitions. Below is the HTML snippet:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
<script type="text/javascript" src="jquery-1.11.1.js"></script>
<script type="text/javascript" src="slider.js"></script>
<style>
* { margin: 0; padding: 0; }
#sliderwrapper { width: 1400px; height: 350px; overflow: hidden; position:relative;}
#sliderlist { list-style: none; left: 0px; position:absolute; width:200000em;}
.item { float: left; }
</style>
</head>
<body>
<div id="sliderwrapper">
<ul id="sliderlist">
<li class="item 1">
<div><img src="img1.png" /></div>
</li>
<li class="item 2">
<div><img src="img2.png" /></div>
</li>
<li class="item 3">
<div><img src="img3.png" /></div>
</li>
</ul>
</div>
</body>
</html>
And here is my implementation using jQuery:
$(document).ready(function () {
setInterval(slide, 1000);
function slide() {
var left = $('#sliderlist').css('left');
left = left.substring(0, left.length - 2);
if (left <= -2800) {
/*var slide = $('#sliderlist li:first');
$('#sliderlist').children('li:first').remove();
$('#sliderlist').append(slide);*/
$('#sliderlist').css('left', '0px');
$('#sliderlist').animate({ left: "-=1400" }, "slow", "swing");
}
else {
$('#sliderlist').animate({ left: "-=1400" }, "slow", "swing");
}
}
});
Every second, the slide function is triggered, animating the list to the left. Upon reaching the last slide (-2800px), it's crucial for the first slide to reappear seamlessly instead of suddenly popping up. Trying different solutions like setting the left property to 0px or constantly removing and appending items resulted in a jarring animation.