MrJRuck
MrJRuck

Reputation: 35

How do I make it so when I click a button my image changes?

I tried to create a function where when the button is clicked the source of the image changed, but it didn't work.

<img
   class="bowgart"
   id="bowgart"
   src="C:\Users\jbrir\Documents\BowgartWebsite2\images\bowgart.png"
   alt="Bowgart"
/>
<script>
   function imgOpen() {
      document.getElementById("bowgart").src = "C:UsersjbrirDocumentsBowgartWebsite2imagesBowgart_open.jpeg";
   }
</script>

Upvotes: 1

Views: 315

Answers (2)

SnappyRiffs
SnappyRiffs

Reputation: 171

I recommend using this code:

<!DOCTYPE html>
<html>
<body>


<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the light</button>

<img id="myImage" src="pic_bulboff.gif" style="width:100px">

<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the light</button>

</body>
</html>

The way how this code works is that when you click the button it changes the source of the image(you do have to have both images) and applies that to the image. And if that was confusing to you then here is a simpler way of saying that: if the image was off and you click the 'on' button it will change to image to on else it does not do anything and the same if it was on. And this is just an example so apply this to your images.

Upvotes: 0

Barmar
Barmar

Reputation: 780818

The src needs to be a valid URL. You're missing the file: URL scheme and all the / delimiters in the pathname.

function imgOpen() {
  document.getElementById("bowgart").src =
    "file:///C:/Users/jbrir/Documents/Bowgart/Website2/images/Bowgart_open.jpeg";
}

Upvotes: 2

Related Questions