0

I have been trying to use javascript to change the image on a webpage I have made. so far my code dosn't do anything at all when I click on the original image. this is my first experiment with JS in a html doc so i could be something simple about how i have to use it.

<h1>heading name</h1>
<div>
    <img alt="alt text"title='hover over text'id='chango'src="images/rsz_josh.jpg"onclick="changeImage()"/>
    <script language="javascript">
        var changeImage = function(){
            img1="images/rsz_josh.jpg";
            img2="images/rsz_josh2.jpg";
            img3="images/rsz_josh3.jpg";

            switch(document.getElementById('chango').src){
                case img1:
                    document.getElementById("chango").src=img2;
                break;
                case img2:
                    document.getElementById("chango").src=img3;
                break;
                default:
                    document.getElementById("chango").src=img1;
                break;
            };
        };
    </script>
</div>
2
  • 1
    jsfiddle.net/nbDm3 Commented Nov 15, 2013 at 22:37
  • Consider replacing the image baseURI with ''. var relative = image.scr.replace(image.baseURI, ''); Commented Nov 15, 2013 at 22:41

1 Answer 1

4

The reason is that document.getElementById('chango').src returns an absolute URL to the image, not a relative one. Thus none of your case statements match.

An idea for fixing that is to split the URL at the slashes and just compare the filename without any path.

EDIT: A slightly easier way would be to use JavaScript's indexOf to see if the URL contains the string. This assumes none of the image names are substrings of other image names.

var changeImage = function(){ 
img1 = "rsz_josh.jpg"; 
img2 = "rsz_josh2.jpg"; 
img3 = "rsz_josh3.jpg"; 
console.log(document.getElementById('chango').src);

imgUrl = document.getElementById('chango').src

if (imgUrl.indexOf(img1) != -1) {
    document.getElementById("chango").src = 'images/' + img2; 
}
else if (imgUrl.indexOf(img2) != -1) {
    document.getElementById("chango").src = 'images/' + img3; 
}

else {
    document.getElementById("chango").src = 'images/' + img1; 
}
Sign up to request clarification or add additional context in comments.

1 Comment

Note: If using getAttribute("src") then the "expected" values (e.g. as written in the markup) ought to be returned. (DOM Properties and HTML Attributes need not be identical or even synchronized.)

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.