Reputation: 21
<img id="myImage" src="C:\Users\81001876\Desktop\Off.png" style="width:100px">
<button onclick="document.getElementById('myImage').src='C:\Users\81001876\Desktop\On.png'">Turn on the light</button>
<button onclick="document.getElementById('myImage').src='C:\Users\81001876\Desktop\Off.png'"> Turn off the light</button>
JavaScript Unable to change the value of the src attribute of an image
Upvotes: 2
Views: 70
Reputation: 19301
The first obstacle to overcome is to have the backslash separators in the image file path recognized in a JavaScript string : if you use \
before a character which is not special in JavaScript strings the backslash is ignored without generating an error.
E.G. Source string "C:\Users\81001876\Desktop\On.png"
is decoded by the JavaScript compiler as
C:Users81001876DesktopOn.png
Choices are to either backslash-escape the backslahes in source code:
C:\\Users\\81001876\\Desktop\\On.png
or convert them to forward slashes because (these days) Windows accepts both forward or backslash separators in file paths. E.G.
C:/Users/81001876/Desktop/On.png
After fixing the backslash issue, Windows absolute filepaths are not valid href
value and should be converted to use the file://
protocol before setting image src
attributes: E.G.
sr="file:///C:/Users/81001876/Desktop/On.png"
Note that file://
protocol based URLs do not accept backslash separators which means there are advantages to converting them to forward slashes early on.
Not withstanding the above, Microsoft used to support windows filenames in some versions of IE. This was and remains non-standard and should not be used outside of a code laboratory.
Upvotes: 1