Reputation: 1026
Anyone have a clue why this code isn't changing my images through 1.fw.png to 5.fw.png?
HTML
<div id="slideshow">
<img id="slider" src="1.fw.png">
</div>
JavaScript
function timer(x){
var timer = setTimeout(function () {switchPic(x);}, 4000);
}
function switchPic(x){
x += 1;
document.getElementById('slider').src = x + ".fw.png";
}
$(document).ready()(function(){
document.getElementById('slider').src = x;
timer(x);
});
A Image Changer with a transition would be a benefit, but just changing the images is the essential requirement.
Upvotes: 1
Views: 237
Reputation: 1026
Thank you user2864740, I re-wrote the code using your information and it loops at the correct number now too.
$(document).ready(function(){
setInterval(function(){
z = document.getElementById('slider').src;
y = z.indexOf(".fw.png");
y = z.slice(y - 1, -7);
x = parseInt(y);
y = (x % 5) + 1;
document.getElementById('slider').src = "/Images/Index/Slider/" + y + ".fw.png";
},4000);
});
Upvotes: 1
Reputation: 61985
x
is a local variable (a parameter) so the increment change does not live past the switchPic
function. If there is a global x
then it is shadowed; otherwise timer(x)
will have resulted in a ReferenceError - make sure do describe what "isn't working" and how such is known.
I might write it like so:
jQuery(function ($) {
var t = -1; // initial value peicked so x is 1 at first interval
function switchIt () {
t++; // change variable caught in closure
var x = (t % 5) + 1; // loops through values in 1..5
$('#slider').attr("src", x + ".fw.png");
}
// set initial image right away
switchIt();
// switch image every 4 seconds, forever
setInterval(switchIt, 4000);
});
Upvotes: 1