1

I am trying to compare an image in javascript. If the image is true it will change to a different image. I wrote an if statement but it doesn't seem to work. Does anyone know how I can achieve this?

function test()
{
imageElement = document.getElementById('pic');
if(imageElement.src == "images/cat_12.gif"){

imageElement.src = "images/press2_12.gif";
}else{

}
}
3
  • Well, what does imageElement.src contain? Commented May 7, 2011 at 16:31
  • 2
    @Pekka The fully qualified URL I assume... .getAttribute('src') would make it work I think. Commented May 7, 2011 at 16:32
  • <td><img src="images/topknobs_12.gif" width="468" name="pic" id="pic" height="575" onclick="test();"/></td> Commented May 7, 2011 at 16:33

2 Answers 2

2
function test(){
    if(imageElement.src.indexOf("images/cat_12.gif") != -1){
       //
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

src will be converted to full URL when you read it from Javascript. You may try to extract the filename instead, e.g. img.src.substr(img.src.lastIndexOf('/')).

A better solution would be use classes and CSS background switch between images.

3 Comments

it doesn't seem to work function test() { img = document.getElementById('pic'); if(img.src.indexOf('images/cat_12.gif')){ imageElement.src = "images/press2_12.gif"; }else{ } }
And img.src.substr(img.src.lastIndexOf('/')) doesn't work either it lets all the images through as if the if doesn't apply.
please supply another solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.