简体   繁体   中英

Change image onclick using javascript

Here's my problem:

I am new to Javascript and I am trying to make my image change on click.

It's a simple counter game that does a 2 frame animation of squidward hitting the dab.

So far I have got the counter to work but I cannot get the image to change on click as well. Also, it's going to have to change back to the original image so that it can be clicked and counted again.

  <html lang="en">
 <head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="./style.css">
<title>Document</title>
</head>
 <body>
<div class="container">

        <button onclick="dabMan()"><img src="./squid-dab1.gif"> . 
        </button>
        <br><br>
        How many dabs??
        <input type="text" id="text">

</div>


<script src="./script.js"></script>


  </body>
 </html>

var dabcount = 0;

function dabMan() {
dabcount = dabcount + 1
document.getElementById('text').value = dabcount;
console.log("dabMan", dabMan)

document.getElementById("./squid-dab1.gif") .src = "./squid-dab2.gif";
console.log("changeimage", dabMan)
 }

instead of using the "onclick(){}" attribute in your html, write an event listener in js. Assuming your image tag is like this:

<img src='./squid-dab1.gif' id='myImage'>

Note: Javascript needs to know how to find your image... Hence the ID

Your javascript code should look like this:

<script>
    var image = document.getElementById('myImage');

    image.addEventListener('click', function(){
        changeImage();
    });

    function changeImage(){
        image.src = './squid-dab2.gif';
    }
</script>

That will make it so that when you click the image, it will change. If you wanted a button to do that, simply create a button with the id "myImage" instead like so:

<button id='myImage'>Click me to change the picture</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM