jOakes90
jOakes90

Reputation: 5

changing <img> tag src with javascript

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>

Upvotes: 0

Views: 2260

Answers (1)

Jud
Jud

Reputation: 1188

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; 
}

Upvotes: 4

Related Questions