Reputation: 31
I apologise if it sounds similar to a previous question, but I've gone over those similar questions and I still can't figure out what the problem is with my code. it's petty simple yet it doesn't work. I have an image. I want it to change to a second image when I click on it, and to a third image when I click on the second image. and then, I want it to change back to the first image when the third image is clicked.
html:
<img id="narrow" class="item" src="images/joe2.jpg" style="cursor:pointer" onclick="changeImage(this);">
javascipt:
function changeImage(imgl) {
if(imgl.src=="images/joe2.jpg") {
imgl.src="images/stray_cat.jpg";
}
else if (imgl.src=="images/stray_cat.jpg") {
imgl.src="images/mathewgarber.jpg";
}
else // (imgl.src=="images/mathewgarber.jpg") {
imgl.src="images/joe2.jpg";
}
}
what happens is that nothing happens when I click on the first image. thanks for your help.
Upvotes: 1
Views: 316
Reputation: 477
As dsfq above said, the image src url will be relative, including the site host.
function changeImage(imgl) {
if (imgl.src.indexOf('images/joe2.jpg') > -1) {
imgl.src = "images/stray_cat.jpg";
} else if (imgl.src.indexOf("images/stray_cat.jpg") > -1) {
imgl.src = "images/mathewgarber.jpg";
} else // (imgl.src=="images/mathewgarber.jpg")
{
imgl.src = "images/joe2.jpg";
}
}
If you have your heart set on your method, you can use a indexOf check to determine if the image name is part of the full src url.
Upvotes: 0
Reputation: 193261
Try something like this:
var images = [
'http://lorempixel.com/100/100/nature/1',
'http://lorempixel.com/100/100/nature/2',
'http://lorempixel.com/100/100/nature/3'
],
i = 0;
function changeImage(img) {
img.src = images[++i % images.length];
}
Comparing image src
with a string is not very reliable because it can contain full domain and protocol. Instead you can store images in array and use %
operator which is very useful for such kind of cycling.
Upvotes: 3
Reputation: 17064
First of all you have the last {
commented out by your imgl.src=="images/mathewgarber.jpg"
).
Secondly, the img1.src
gives you a different string, take a look at this Demo
You should check for the src like this:
if(imgl.src.indexOf("images/joe2.jpg") > -1)
Upvotes: 0