Vrutin
12-07-2012, 07:51 PM
Hello, Basically I am coding a simple JavaScript coded slideshow. Everything seems to work. However, what's happening is that I can go "previous" but I have to press twice to get it to work:
Here is my code:
var index = 0;
var img;
var slideName;
function moveToNextSlide() {
img = document.getElementById("img1");
slideName = "images/slide" + ++index + ".png";
img.src = slideName;
if (index == 3) {
index = 0;
}
}
function moveToPreviousSlide() {
if (index == 0) {
index = 3;
}
slideName = "images/slide" + index-- + ".png";
img.src = slideName;
}
More Info:
I am experimenting this with 3 images.
Thanks In Advance..
WolfShade
12-07-2012, 08:01 PM
moveToPreviousSlide shouldn't work at all, I don't think.. you don't have img = document.getElementById("img1"); in it.
You have slide0.png through slide2.png?
Vrutin
12-07-2012, 08:06 PM
moveToPreviousSlide shouldn't work at all, I don't think.. you don't have img = document.getElementById("img1"); in it.
You have slide0.png through slide2.png?
Hey, Thanks for input..
moveToPreviousSlide is working. I have made 'img' a global variable.
The slide names are slide1.png through slide3.png
Thanks
WolfShade
12-07-2012, 08:48 PM
Is it working, now? I think the math MIGHT be off.
Vrutin
12-07-2012, 11:17 PM
Is it working, now? I think the math MIGHT be off.
Hey, It wasn't working at the point you asked...
Here is the working code, for anyone in future looking at this post:
var index = 0;
var img;
var slideName;
function moveToNextSlide() {
img = document.getElementById("img1");
if (index == 3) {
index = 0;
slideName = "images/slide" + index + ".png";
}
slideName = "images/slide" + ++index + ".png";
img.src = slideName;
}
function moveToPreviousSlide() {
slideName = "images/slide" + --index + ".png";
if (index == 0) {
index = 3;
slideName = "images/slide" + index + ".png";
}
img.src = slideName;
}
Old Pedant
12-08-2012, 03:09 AM
That works, but it really kind of much bigger and uglier than needed.
Try something like this:
var MINSLIDE = 0;
var MAXSLIDE = 2; // adjust those as needed
var curSlide = MINSLIDE;
function moveSlide( byWhat )
{
curSlide += byWhat;
if ( curSlide > MAXSLIDE ) { curSlide = MINSLIDE; }
else if ( curSlide < MINSLIDE ) { curslide = MAXSLIDE; }
document.getElementById("img1") = "images/slide" + curSlide + ".png";
}
And now, instead of calling moveToNextSlide() or moveToPreviousSlide() you call moveSlide(1) and moveSlide(-1).
And the beauty of this is that you can even call moveSlide(0) to start everything up with the first slide.
Oh...and this works whether the slides are number 0 through N or 1 through N. Or even 73 through 122, for that matter.