Nick Clark
Nick Clark

Reputation: 1446

Change Images on Click (Cycle through 3 images)

I have and 3 images that I need to change like so: Image 1 > Image 2 > Image 3 > Image 1 and so on in that loop.

JavaScript

function changeImage() {

    if (document.getElementById("imgClickAndChange").src = "Webfiles/SUB15_15A.bmp") 
    {
        document.getElementById("imgClickAndChange").src = "Webfiles/SUB15.bmp";
    }

    else if (document.getElementById("imgClickAndChange").src = "Webfiles/SUB15.bmp")
    {
        document.getElementById("imgClickAndChange").src = "Webfiles/SUB15A.bmp";
    }

    else
    {
        document.getElementById("imgClickAndChange").src = "Webfiles/SUB15_15A.bmp"
    }
}

HTML

<img src="Webfiles/SUB15_15A.bmp" id="imgClickAndChange" onclick="changeImage()" usemap="#SUB15" />

Any suggestions are appreciated. Everything else I have tried has not worked.

Upvotes: 1

Views: 5235

Answers (3)

Musa
Musa

Reputation: 97672

You're using an assignment operator instead of a comparison operator in your if statements

if (document.getElementById("imgClickAndChange").src = "Webfiles/SUB15_15A.bmp") 

should be

if (document.getElementById("imgClickAndChange").src == "Webfiles/SUB15_15A.bmp") 
//                                                    ^

Also using the src property as a comparison might not be a good idea as the browser might have it as an absolute url rather than the relative url in the html src attribute, which might be better to use.

if (document.getElementById("imgClickAndChange").getAttribute("src") == "Webfiles/SUB15_15A.bmp") 

http://jsfiddle.net/rzannv33/

I'd suggest using a variable to keep the state of the image, like a counter probably.

Upvotes: 1

Md Ashaduzzaman
Md Ashaduzzaman

Reputation: 4038

On img click change the src attribute of the img tag and using a counter would help more rather checking the previous image source.

HTML :

<img src="http://www.clipartbest.com/cliparts/RiA/66K/RiA66KbMT.png" id="imgClickAndChange" onclick="changeImage()" usemap="#SUB15" />

JS :

var counter = 1;

imgClickAndChange.onclick = function(){
    if(counter == 0){
        document.getElementById("imgClickAndChange").src = "http://www.clipartbest.com/cliparts/RiA/66K/RiA66KbMT.png";
        counter++;
    }
    else if(counter == 1){
        document.getElementById("imgClickAndChange").src = "http://www.wpclipart.com/education/animal_numbers/animal_number_2.png";
        counter++;
    }
    else if(counter == 2){
        document.getElementById("imgClickAndChange").src = "http://upload.wikimedia.org/wikipedia/commons/thumb/e/e4/Number_3_in_yellow_rounded_square.svg/512px-Number_3_in_yellow_rounded_square.svg.png";
        counter = 0;
    }
};

jsFiddle

Upvotes: 1

robotcookies
robotcookies

Reputation: 1059

Use the triple equals '===' to check when if the src is equivalent or not. Using one equal '=' means you are assigning the value so you'll never get past the first if.

Upvotes: 1

Related Questions