简体   繁体   中英

Trying to switch images using a toggle button in vanilla JS

I'm not quite sure why my code isn't working at this point. I am trying to make an Instagram like button. I have an image of a black heart and when double clicked on I want to switch it to another image of a red heart. I've dug around here and there but couldn't quite pin point the problem. The code snippet works but it does not work when I run it in my project.

 const button = document.querySelector('#like'); document.querySelector('button').addEventListener('dblclick', (e) => { if (button.src == "https://www.w3schools.com/html/img_chania.jpg") { button.src = "https://www.w3schools.com/html/pic_trulli.jpg"; } else { button.src = "https://www.w3schools.com/html/img_chania.jpg"; } });
 .under-image-nav button { border: none; width: 30px; }
 <nav class="under-image-nav"> <button><img id="like" src="https://www.w3schools.com/html/img_chania.jpg" alt="like button"> </button> </nav>

You should attach the event listener to the button instead.

 const img = document.querySelector('#like'); document.querySelector('button').addEventListener('dblclick', (e) => { if (img.src == "https://www.w3schools.com/html/pic_trulli.jpg") { img.src = "https://www.w3schools.com/html/img_chania.jpg"; } else { img.src = "https://www.w3schools.com/html/pic_trulli.jpg"; } });
 <button><img id="like" src="https://www.w3schools.com/html/pic_trulli.jpg" alt="like button" width="100" height="100"></button>

I got rid of the button and simply allowed javascript to control the source of the image.

To shorten the code, I used a ternary operator

 let heartEl = document.querySelector(".heart"); const fullHeart = 'https://external-content.duckduckgo.com/iu/?u=http%3A%2F%2Ffrogermcs.github.io%2Fimages%2F6%2Fheart_red.png&f=1&nofb=1"' const emptyHeart = 'https://freeiconshop.com/wp-content/uploads/edd/heart-outline.png' heartEl.addEventListener("dblclick", () => { heartEl.src == emptyHeart? heartEl.src = fullHeart: heartEl.src = emptyHeart });
 <img class='heart' src='https://freeiconshop.com/wp-content/uploads/edd/heart-outline.png'>

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