Trying to make something simple in JS. Lets say I have two images, I want the page to load each image randomly. I want the two images to be swapped, when it gets clicked, it should change to the other image. How can I do this? Thanks
2 Answers
Here's plain javascript code (no frameworks used) that randomly loads one of the images in the imgs array as the initial image and then cycles through different images on each press of the button and a jsfiddle where you can see it work: http://jsfiddle.net/jfriend00/R7nUa/:
var imgs = [
"http://photos.smugmug.com/photos/344291068_HdnTo-Th.jpg",
"http://photos.smugmug.com/photos/344290962_h6JjS-Th.jpg",
"http://photos.smugmug.com/photos/344290515_bWVzK-Th.jpg"
];
// select a random image from the img URL array
function getRandomImage() {
var index = Math.floor(Math.random() * imgs.length);
return(imgs[index]);
}
// create image tag with random image
function initImage() {
var img = new Image();
img.id = "dynImage";
img.src = getRandomImage();
var o = document.getElementById("imageHolder");
o.appendChild(img);
}
// given the current URL, get the next URL in the array,
// wrapping back to beginning if needed
function nextImage(current) {
for (var i = 0; i < imgs.length; i++) {
if (imgs[i] == current) {
i++;
if (i >= imgs.length) {
i = 0;
}
return(i);
}
}
return(0);
}
// put a different image into the image tag
function swapImage() {
var o = document.getElementById("dynImage");
var next = nextImage(o.src);
o.src = imgs[next];
}
// initialize the button event handler
function initButton() {
var o = document.getElementById("swap");
if (o.addEventListener) {
o.addEventListener("click", swapImage);
} else {
o.attachEvent("onclick", swapImage);
}
}
initImage();
initButton();
You can put as many URLs into the imgs array as you want. You can see this working here: http://jsfiddle.net/jfriend00/R7nUa/ where I've also added preloading so the swap is instant when you press the button.
4 Comments
Jared Farrish
Nice! Although I have a feeling it's over the OP's level of understanding.
:sJared Farrish
This particular functionality was one of the first things I ever did in Javascript, way back in 2002-2003. Ahh, the good 'ol days.
jfriend00
@JaredFarrish - I figure the best way to learn is to look at code related to your problem that's a little more advanced than you know how to write.
Jared Farrish
I don't disagree (and that wasn't meant as criticism), but it's probably a couple levels above, at least as far as I can tell.
You need this line somewhere in your script
var IMG1 = document.getElementById("IMG1");
2 Comments
Jared Farrish
@Rich2233 - Well sure. You should probably ask another question, though.
Rich2233
@Jared - Sorry about this comment being off topic, but I'm not sure how to send message here. Could you please take a look at my question here: stackoverflow.com/questions/7869514/dhtml-script-verification Thanks, Jared.