0

I'm doing an HTML assignment for a class at university and I was stuck on a problem asking me to create a button with the label “Change color!”. When the button is pressed, a script will execute causing the “green_parakeet.jpg” image to be replaced with “blue_parakeet.jpg”.

When I emailed the professor, she said for me to add onclick="statement" property, e.g. you can call a function here as shown in the example from the LX12 document <button onclick="f(x);">. Then you can write a script language to set up the function in a way that img tag should change src property value to a new one.

Here's my HTML code so far

<img src = "green_parakeet.jpg">
<button> Change Color! </button>

I can't figure out what to do next.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Dina Chen
  • 3
  • 1
  • You need either JavaScrpt / jQuery. There are a ton of tutorials out there to show you how to trigger some action when you click a button. There are also other questions on this site that will help you. Start with a search like "how to change an image on button click in javascript" – devlin carnate Aug 05 '22 at 18:20
  • 1
    Does this answer your question? [Change image when clicking button](https://stackoverflow.com/questions/19609387/change-image-when-clicking-button) – devlin carnate Aug 05 '22 at 18:22

1 Answers1

1

I have created this code according to this.

<script>
function change() {
document.getElementById("image").src = 'blue_parakeet.jpg';
 }
 </script>
 <img id="image" src = "green_parakeet.jpg">
<button onclick="change()"> Change Color! </button>

edit: The code below will remove the onclick.

<script>
function change() {
document.getElementById("image").src = 'blue_parakeet.jpg';
document.getElementById('button').removeAttribute("onclick");
}
</script>
<img id="image" src="green_parakeet.jpg">
<button id="button" onclick="change()"> Change Color! </button>
wp-ap
  • 109
  • 1
  • 8
  • Thanks, but it also says that any additional button presses should not do anything to the image, just the first button press. – Dina Chen Aug 05 '22 at 19:05
  • Then add id="button" to the button and add this inside the function. `document.getElementById('button').removeAttribute("onclick");` It will remove the onclick from the button and button will do nothing. – wp-ap Aug 05 '22 at 19:20
  • So the whole thing from start to finish is like this? ** – Dina Chen Aug 05 '22 at 19:41
  • I mean ignore the two astericks before and after the code. – Dina Chen Aug 05 '22 at 19:49
  • ` ` – wp-ap Aug 05 '22 at 19:54