I am attempting to write an simple function in an HTML page which displays the image and there are few buttons which change the image I have used the "document.getElementById(‘myImage’).src= " command to change it but there is no image shows after I click the image. The same image is loading properly using the tag. The same button works if I use a link direct taken from google. Below I have pasted the code. Any suggestions are appreciated.
<!IDOCTYPE HTML>
<html>
<body>
<h2> This page shows changing emotions using various buttons </h2>
<img id = "image" src = "pathangry.jpg" style = "width:100px">
<button onclick = 'document.getElementById("image").src = "pathenvy.jpg"'>Envy</button>
<button onclick = 'document.getElementById("image").src = "pathangry.jpg"'>Angry</button>
<button onclick = 'document.getElementById("image").src = "pathsad.jpg"'>Sad</button>
<button onclick = 'document.getElementById("image").src = "pathembarassed.jpg"'>Embarassed</button>
<button onclick = 'document.getElementById("image").src = "pathhappy.jpg"'>Happy</button>
<button onclick = 'document.getElementById("image").src = "pathanxiety.jpg"'>Anxiety</button>
</body>
</html>
Tried links from Google it works but local images does not work in the on click function Thank you!
3
Answers
The issue you’re encountering is likely due to the backslashes () used in the file paths. In HTML and JavaScript, file paths should use forward slashes (/). Backslashes are not valid path separators in URLs.
Backslash in Strings
The reason it doesn’t work is because a backslash within a string acts as an escape sequence in JavaScript and other languages.
So
"pathangry.jpg"
is escaped topathangry.jpg
and the image fails to display.Backslash in Attributes
However, the backslash has no effect when used in an attribute.
The browser converts the src to an absolute url and
<img src="pathangry.jpg">
becomes"../path/angry.jpg"
Note that the browser replaces the backslash with a forward slash. And the image displays as expected.Run the test to understand how the slashes affect the src.
Don’t use inline event handlers. Details are commented in the example.