Home > Back-end >  How do I make it so when I click a button my image changes?
How do I make it so when I click a button my image changes?

Time:12-23

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

<img
   
   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>

CodePudding user response:

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";
}

CodePudding user response:

I recommend using this code:

<!DOCTYPE html>
<html>
<body>

<h2>What Can JavaScript Do?</h2>

<p>JavaScript can change HTML attribute values.</p>

<p>In this case JavaScript changes the value of the src (source) attribute of an image.</p>

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

  • Related