0

Currently i am trying to change an image on click to another image. I have managed to do so with the following code: (working)

 <img id="inv1imgid" src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a2/X_mark.svg/525px-X_mark.svg.png" onclick="switchImage(this)" width="36" height="36" />
    var preselected = "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a2/X_mark.svg/525px-X_mark.svg.png";
var selected = "https://cdn.pixabay.com/photo/2016/03/31/14/37/check-mark-1292787_960_720.png";

var switchImage = function(image) {
    if(image.src == preselected) {
        image.src = selected;
    } else {
        image.src = preselected;
    }
};

This work, but only when i give the img src an URL. I want to use: src = "selectedimg.png" and src = "preselectedimg.png", however when i do this it cant seem to find the image as no image is switched. Yes the images have those names in my wwwroot folder.

  • you images must be the same path with the file calling it if you want it like that – Roljhon Jan 27 '17 at 19:20
  • 1
    Possible duplicate of [javascript dynamically change the location of image src - NO JQuery](http://stackoverflow.com/questions/11930079/javascript-dynamically-change-the-location-of-image-src-no-jquery) – Stephen P Jan 27 '17 at 19:43

2 Answers2

0

If this page is inside a folder on root, the path will be relative to the current directory unless you use

img.src = '/selectedimg.png'

for example...

You can also reset the base url of the current page by using the <base> html tag like so

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>This is an example for the <base> element</title>
        <base href="http://www.example.com/news/index.html">
    </head>
    <body>
        <p>Visit the <a href="archives.html">archives</a>.</p>
    </body>
</html>

EDIT:

Also take a look at Defining root of HTML in a folder within the site root folder

Community
  • 1
  • 1
  • Turns out what i needed was for it to: ' show my full page url/ + selectedimg.png ' –  Jan 27 '17 at 19:54
0

Let's say you have two images.

<img src="image1.jpg" id="img1" />
<img src="image2.jpg" id="img2" />

You want to click on img2 and change img1, from what I understand. So what you need is this little addition in img2 tag:

<img src="image2.jpg" id="img2" 
 onclick="document.getElementById('img1').src = 'image3.jpg'" />

That's it. I hope it is helpful :)

kylethedeveloper
  • 41
  • 1
  • 1
  • 10