Miruza Miruza - 1 month ago 16
HTML Question

Want to change image src via button by javascript but code does not work

I am new to javascript. I just want to change the source of image to different one when user presses one of the 3 buttons. These buttons has different source. I don't know what is wrong with my code, apparantly it does not work...

<!doctype html>
<head>
<title>Change image with button</title>
</head>

<body>
<h3>Click on the buttons to change image</h3><br/><br/><br/>
<img id="photo_mine" src="01.bmp"/><br/><br/>
<button id="one">1</button>
<button id="two">2</button>
<button id="three">3</button>

<script>
document.getElementById("one").addEventListener("click", ch_image("01.bmp"), false);
document.getElementById("two").addEventListener("click", ch_image("02.png"), false);
document.getElementById("three").addEventListener("click", ch_image("03.jpg"), false);


function ch_image(source_path) {
var img_but = document.getElementById("photo_mine");
img_but.src = source_path;
}

</script>
</body>


PS: Edited all "Document" to "document" and fixed a syntax error.
Now it's weird. The page loads always with the 3rd image(03.jpg) opened, and pressing different buttons do not change the image.

Answer

Aside from the mistake pointed out in the comments (Document != document), your main issue is the fact that you're calling ch_image earlier than you think you are. addEventListener expects you to pass in a function, but you're actually calling ch_image and then passing in the result. Your code should actually look like this:

<!doctype html>
<head>
    <title>Change image with button</title>
</head>

<body>
    <h3>Click on the buttons to change image</h3><br/><br/><br/>
    <img id="photo_mine" src="01.bmp"/><br/><br/>
    <button id="one">1</button> 
    <button id="two">2</button> 
    <button id="three">3</button>

    <script>
        document.getElementById("one").addEventListener("click", function () {
            ch_image("01.bmp");
        });

        document.getElementById("two").addEventListener("click", function () {
            ch_image("02.bmp");
        });

        document.getElementById("three").addEventListener("click", function () {
            ch_image("03.bmp");
        });


        function ch_image(source_path) {
            var img_but = document.getElementById("photo_mine");
            img_but.src = source_path;
        }

    </script>
</body>

(Additionally, I removed the false from each call, as that's the default anyway - you don't need to specify it every time!)