skip to Main Content

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


  1. 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.

    <!DOCTYPE HTML>
    <html>
    <body>
    <h2> This page shows changing emotions using various buttons </h2>
    
    <img id="image" src="path/angry.jpg" style="width:100px">
    
    <button onclick='document.getElementById("image").src = "path/envy.jpg"'>Envy</button>
    <button onclick='document.getElementById("image").src = "path/angry.jpg"'>Angry</button>
    <button onclick='document.getElementById("image").src = "path/sad.jpg"'>Sad</button>
    <button onclick='document.getElementById("image").src = "path/embarrassed.jpg"'>Embarrassed</button>
    <button onclick='document.getElementById("image").src = "path/happy.jpg"'>Happy</button>
    <button onclick='document.getElementById("image").src = "path/anxiety.jpg"'>Anxiety</button>
    
    </body>
    </html>
    
    Login or Signup to reply.
  2. 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 to pathangry.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.

    const image = document.getElementById('image');
    
    console.log(`attribute: ${image.src}`); 
    
    
    [ 'pathangry.jpg',   // <-- fails
      'path\angry.jpg',  // <-- works
      'path/angry.jpg'    // <-- works
    ].forEach(src => {
    
      image.src = src;
      console.log(`string: ${image.src}`)
    
    })
    <img id="image" src="pathangry.jpg" style="display:none">
    Login or Signup to reply.
  3. Don’t use inline event handlers. Details are commented in the example.

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title></title>
      <style>
        img {
          display: block;
          width: 300px;
          height: 300px;
          margin: 20px auto;
          cursor: pointer
        }
      </style>
    </head>
    
    <body>
      <img src="https://i.ibb.co/bBGX3Sq/static.gif">
      <script>
        // Assign a counter outside of function
        let i = 0;
        // Have the URLs of the the images in an array
        const pix = [
          "https://i.ibb.co/c1PtcM7/matrix1.gif",
          "https://i.ibb.co/FHRS8Gx/stars.gif",
          "https://i.ibb.co/bBGX3Sq/static.gif"
        ];
        // This is the callback function that will be invoked at every click
        function changeSrc(e) {
          // Increment the counter
          i++;
          // If the count equals to or exceeds the number of URLs in pix array...
          if (i >= pix.length) {
            // Reset the counter back to 0
            i = 0;
          }
          // Change the src of the <img> to the URL at the index of "i" in array pix
          this.src = pix[i];
        }
    
        document.querySelector("img").onclick = changeSrc;
      </script>
    </body>
    
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search