Akshay Sable
Akshay Sable

Reputation: 31

Unable to change image source

Why am I unable to change the image source?

<img id="myImgId" alt="" onclick="changeImage()" src="C:\Users\USER\Desktop\GRAPHICS\photo2.jpg" width="1200" height="400" />

<script>
function changeImage() {
var image = document.getElementById("myImgId");
if (image.src.match("C:\Users\USER\Desktop\GRAPHICS\photo2.jpg")) {
    image.src="C:\Users\USER\Desktop\GRAPHICS\photo3.jpg";
} else {
    image.src="C:\Users\USER\Desktop\GRAPHICS\photo1.jpg";
}
}
</script>

Upvotes: 2

Views: 66

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074028

Three reasons:

  1. Because \ in JavaScript strings (as in my programming languages) is an escape character, so your string doesn't actually have any backslashes in it.

    To have an actual backslash in a string literal, you need to escape it — with a backslash.

  2. The src property is a fully-resolved URL, which will start with a protocol, in this case file:, and have normalized slashes (backslashes become / in normalized URLs).

  3. String#match expects a regular expression. You're passing it a string, and so the string will be run through new RegExp, which means that even with \\, you still won't have backslashes in that regex because backslash is special in regexes, too (as are ., so that .jpg will be an issue). You'd need \\\\ just to have a single literal backslash in the resulting regex.

Here's a possible fix:

function changeImage() {
    var image = document.getElementById("myImgId");
    if (/photo2\.jpg$/.test(image.src)) {
        image.src = "C:\\Users\\USER\\Desktop\\GRAPHICS\\photo3.jpg";
    } else {
        image.src = "C:\\Users\\USER\\Desktop\\GRAPHICS\\photo1.jpg";
    }
}

Those Windows paths will get converted to URLs on assignment.

Or perhaps you'd like to cycle through the three images:

function changeImage() {
    var image = document.getElementById("myImgId");
    image.src = image.src.replace(/photo(\d)\.jpg$/, function(m, c0) {
        var next = +c0 % 3 + 1;
        return "photo" + next + ".jpg";
    });
}

Each time you call it, that will advance to the next photo, wrapping-around from 3 to 1.

Upvotes: 5

Related Questions