skip to Main Content

I’m learning Javascript and don’t understand why the following won’t switch out when I reference the picture’s ID. The URL works fine, but for simplicity and clarity’s sake, I’d prefer to use the ID assigned. I’m trying to replace the "MarioImg" wiht "Img_1" by clicking on "MarioImg". It’s a long document, so I’ll shorted the code down:

<img id="MarioImg" class="mariowonder" src="https://media.gamestop.com/i/gamestop/20006717?$pdp$$&fmt=webp" ;/>

<img onclick="SwitchImg1()" id="Img_1" class="mariosideimg" src="https://media.gamestop.com/i/gamestop/20006717?$pdp$$&fmt=webp" />

<script>
  function SwitchImg1() {
    document.getElementById("MarioImg").src =
      document.getElementById("Img_1");
  }
</script>

The url works if I only use that. However, when using the ID a small white and green paper shows up without the image. I think it’s not loading in?

2

Answers


  1. Chosen as BEST ANSWER

    I forgot to add the .src element to the end of my Img_1 reference. Doing this fixed it!


  2. You need to use temp variable for src of the 1st img tag

    <img id="MarioImg" class="mariowonder" src="https://unsplash.com/photos/RgplfXbxLFs"/>
    
    <img onclick="SwitchImg1()" id="Img_1" class="mariosideimg" src="https://unsplash.com/photos/X-Far-t1woI" />
    </body>
    
    <script>
      function SwitchImg1() {
        src1 = document.getElementById("MarioImg").src;
        document.getElementById("MarioImg").src = document.getElementById("Img_1").src;
        document.getElementById("Img_1").src = src1
      }
    
    </script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search