Swap image with onclick - HTML and JS

Asked

Viewed 236 times

-2

I am developing a code to change the image when it is clicked, this with several Divs, ids to be exchanged for the same image. I even managed to change the first one, but the rest do not change, because of the ID. But I could not think or find anything similar.

<img src="images/coração.png" class="checkbox-7" id="changeimg" onclick="changeImg();">                 
                    
<img src="images/coração.png" class="checkbox-7" id="changeimg2" onclick="changeImg();">    
                    
<img src="images/coração.png" class="checkbox-7" id="changeimg3" onclick="changeImg();">    
                    
<img src="images/coração.png" class="checkbox-7" id="changeimg4" onclick="changeImg();">    
                    
function changeImg () {
    document.getElementById("changeimg").src="images/coracao-preenchido.png";
}
  • Study on foreach()

  • You want to exchange all images by clicking on one of them, or change only the one that was clicked?

  • @user140828 exchange only the image that was clicked.

2 answers

0


<img src="https://i2.wp.com/static3.mangalivre.com/capas/aP9npfL-OIarDT5hIOek-Q/7794/external_cover.jpg?quality=100" class="checkbox-7" onclick="changeImg(this)">                 
                    
<img src="https://i2.wp.com/static3.mangalivre.com/capas/aP9npfL-OIarDT5hIOek-Q/7794/external_cover.jpg?quality=100" class="checkbox-7"  onclick="changeImg(this)">    
                    
<img src="https://i2.wp.com/static3.mangalivre.com/capas/aP9npfL-OIarDT5hIOek-Q/7794/external_cover.jpg?quality=100" class="checkbox-7"  onclick="changeImg(this)">    
                    
<img src="https://i2.wp.com/static3.mangalivre.com/capas/aP9npfL-OIarDT5hIOek-Q/7794/external_cover.jpg?quality=100" class="checkbox-7" onclick="changeImg(this)">    

<script>
function changeImg (el) {
 el.src='https://i2.wp.com/static3.mangalivre.com/capas/5mv8yie5DOFf_A_P0pmSKQ/10310/external_cover.jpg?quality=100';
 
}
</script>

  • @Leticia in case it doesn’t work or you want to change something let me know I’ll check the code I posted

  • It worked, thank you very much!!!!!!!

0

<img src="images/coração.jpg" class="checkbox-7" id="changeimg" onclick="changeImg(event)">                 
                    
<img src="images/coração.jpg" class="checkbox-7" id="changeimg2" onclick="changeImg(event)">    
                    
<img src="images/coração.jpg" class="checkbox-7" id="changeimg3" onclick="changeImg(event)">    
                    
<img src="images/coração.jpg" class="checkbox-7" id="changeimg4" onclick="changeImg(event)">

<script>
    function changeImg (event) {
        id = event.target.id
        document.getElementById(id).src = "images/coraçãoPreenchidojpg.jpg"
    }
    
</script>

  • It worked, thank you very much!!!!!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.