Reputation: 791
I want to create a continuous scrolling image slider using jquery. This is as far as I can get. I don't quite understand how to pass function parameters especially when I'm using this
. The idea is to start an animation and move an image from just outside a div to the other side just outside of view again then reset its position. the image that follows will start its animation as soon as the image before it has passed the starting point and so on. (I figured out the speed was 250px/sec so the width of the current element divided by 250 should give me the time I should wait to initiate the next animation, I think...)
<div class="slideshow" style="position: absolute; top: 220px;left: 50%; margin-left: -700px;height: 600px; width: 1400px; z-index: 2;">
<img src="img2.jpg" id="img2" class="slideshowImages">
<img src="img3.jpg" id="img3" class="slideshowImages">
<img src="img4.jpg" id="img4" class="slideshowImages">
<img src="img1.jpg" id="img1" class="slideshowImages">
</div>
</body>
<script>
$(document).ready(setTimeout(function() {
var InfiniteRotator =
{
init: function(ident, time)
{
$(ident).animate({"margin-left": "-=2500"},{ duration:10000,easing: 'linear',queue:false, complete:function(){
$(ident).css("margin-left", "1400px");
}
// Animation complete.
}).delay(time);
}
}
var time = 0;
$('div.slideshow').each(function(){
InfiniteRotator.init(this, time);
time = $(this).width()/250;
});
}, 3000));
</script>
Upvotes: 2
Views: 692
Reputation: 36521
$('div.slideshow')
refers to one element (the div containing your images), so calling each
on it will not iterate through your images as your code seems to assume.
$('div.slideshow img').each(function(){
InfiniteRotator.init(this, time);
time = $(this).width()/250;
});
In this altered version, this
refers to the current image element (a nice shortcut jQuery supplies). This code does the same thing:
$('div.slideshow img').each(function(index, element){
InfiniteRotator.init(element, time);
time = $(this).width()/250;
});
If you wanted to "be like jQuery" and allow your InfiniteRotator to access the current image using this
, you could use call
or apply
instead of directly calling your init
method and pass the element as the context (what this
refers to within the called function):
$('div.slideshow img').each(function(index, element){
InfiniteRotator.init.call(element, element, time);
time = $(this).width()/250;
});
var InfiniteRotator =
{
init: function(ident, time)
{
$(this).animate({"margin-left": "-=2500"}, {
duration:10000,
easing: 'linear',
queue:false,
complete:function(){
$(this).css("margin-left", "1400px");
}
}).delay(time);
}
}
Upvotes: 2