Search code examples
htmlcssimagefunctionhtml-helper

How do I change the color of the green parakeet picture to a blue parakeet picture in HTML using a function?


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.


Solution

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