Reputation: 2015
JSFiddle is here...
All right. I'm trying to create a JQuery carousel to display some images of different widths. To help accomplish this, I'm trying to produce a seamless, unending slide to the right on an unordered list containing images. I plan to put images that have passed the threshold behind the rest with the .before property so that it will continue forever. However, I have three problems.
The first problem is that if my JS looks like this...
$(document).ready(function() {
function gallery () {
$("#image").animate({"margin-left":"200px"}, 3000);
}
setInterval(gallery, 3000);
});
It waits 3 seconds, and it only runs once. I did look around to see if I could fix the only running once problem, and I found this...
setInterval() only running function once
And many other questions like it. Always it is the same thing. They are calling the function like this...
setInterval(gallery(), 3000);
in setInterval, instead of like this...
setInterval(gallery, 3000);
So, I know that cannot be the solution. Considering my function already has no parentheses following it, and is being called the correct way. (I think.)
So, logically I tried to fix the next problem, the three second delay. I wrote this...
$(document).ready(function() {
$("#image").animate({"margin-left":"200px"}, 3000);
function gallery () {
$("#image").animate({"margin-left":"200px"}, 3000);
}
setInterval(gallery, 3000);
});
Now it runs instantly when the page loads, however since setInterval was only running once before, I would assume I would get two occurrences of...
$("#image").animate({"margin-left":"200px"}, 3000);
One that was running on load, and the other being run from the "gallery" function by setInterval. This however is not the case. It runs instantly but I only get one occurrence.
My final problem does not have anything to do with setInterval, but I figure I would kill two birds with one stone. Because my unordered list hasa width of 9,999 pixels, does that mean even if I run the animation continuously, eventually I will run out of element to move?
Upvotes: 2
Views: 1145
Reputation: 55750
It looks like it is running only once
$("#image").animate({"margin-left":"200px"}, 3000);
When the function runs for the first time the margin-left:200px
is already set to the attribute provided.
So the next time it runs, there is no change in the margn-left
property. So it looks static
I think you are looking for
$("#image").animate({"margin-left":"+=200"}, 3000);
Using += will increment the value that is provided every time the function runs.
Upvotes: 2