Ragnaroni
Ragnaroni

Reputation: 37

Image doesn't show when changing src attribute

So I have to make a button that changes an image that I have (which I then have to be able to change back to the previous image with a click of the same button). However the image when it changes doesn't show. Here's the code, if it's not well put in keep in mind this is my first using this site.

//FUNCTIONS
    function changerPingouin(pingouin){        
    document.getElementById("pingouin").src='C:\Users\name\Desktop\images1/pingouin_rouge_grand.png';   
}
<body>
    <img src='C:\Users\name\Desktop\images1/pingouin_grand.png' id="pingouin">   
    <img src='C:\Users\name\Desktop\images1/pingouin_rouge_grand.png' id="pingouin_rouge">
<button onclick="changerPingouin();">
        Changer de Pingouin
</button>            

The first image shows and I have other functions that work with it. However when I click the button, it doesn't display the other image. For this reason I haven't started the part where another click of the button changes the image back to the first one "pingouin_grand".Thanks.

Upvotes: 1

Views: 46

Answers (1)

alyssaeliyah
alyssaeliyah

Reputation: 2244

Error:

/C:/UsersnameDesktopimages1/pingouin_rouge_grand.png:1 GET file:///C:/UsersnameDesktopimages1/pingouin_rouge_grand.png net::ERR_FILE_NOT_FOUND Image (async) changerPingouin @ Module_8PLs.html:21 onclick @ Module_8PLs.html:89

From the error, the file is not found because the path read is C:/UsersnameDesktopimages1/pingouin_rouge_grand.png. There are no backslash separating the directories.

The backslash needs to be escaped. In JavaScript, the backslash is used to escape special characters, such as newlines (\n). If you want to use a literal backslash, a double backslash has to be used. Try changing the image source to 'C:\\Users\\name\\Desktop\\images1\\pingouin_rouge_grand.png'. Do the same to the first image.

Upvotes: 1

Related Questions