Home > database >  Switching between 2 images html & javscript
Switching between 2 images html & javscript

Time:01-23

I write this code, when I click on that specifiek place on the image it is going to the next image. so far it is working but i want when i click on the same place again that the previous image is displayed again.

this is not working, how do i fix this?

    <img id="lights-off" src="../images/ABC2.png" style="display: none;">
    <img id="lights-on" src="../images/ABC.png">


    const lightsOff = document.getElementById("lights-off");
    const lightsOn = document.getElementById("lights-on");
    let isChanged = false;
    
    lightsOn.addEventListener("click", function(event){
        if (event.offsetX >= 0 && event.offsetX <= 100 && event.offsetY >= 0 && event.offsetY <= 20) {
            if(!isChanged){
                lightsOff.style.display = "block";
                lightsOn.style.display = "none";
                isChanged = true;
            } else {
                lightsOff.style.display = "none";
                lightsOn.style.display = "block";
                isChanged = false;
            }
        }
    });

I tryed to make some changes but it doenst work

CodePudding user response:

You could assign a single delegated event listener to the page and inspect the event to only process images of interest. By toggling the display property based upon an images current display state you achieve the desired effect I think

let col = document.querySelectorAll('img#lights-on,img#lights-off');

document.addEventListener("click", function(e) {
  if (e.target instanceof HTMLImageElement && e.offsetX >= 0 && e.offsetX <= 100 && e.offsetY >= 0 && e.offsetY <= 20) {
    col.forEach(img => {
      if (img && img.nodeType == 1) {
        img.style.display=( img.style.display == '' || img.style.display == 'block' ) ? 'none' : 'block';
      }
    })
  }
});
img {
  width: 300px;
  border: 1px solid black;
}
<img id="lights-off" src="//www.collinsdictionary.com/images/thumb/apple_158989157_250.jpg" style="display: none;">
<img id="lights-on" src="//upload.wikimedia.org/wikipedia/commons/thumb/8/8a/Banana-Single.jpg/680px-Banana-Single.jpg">

CodePudding user response:

you are listing only to lightsOn you should listen to both of the images:

const lightsOff = document.getElementById("lights-off");
const lightsOn = document.getElementById("lights-on");


function isInBorder(event){
    return event.offsetX >= 0 && event.offsetX <= 100 && event.offsetY >= 0 && event.offsetY <= 20
}

lightsOn.addEventListener("click", function(event){
    if (isInBorder(event)) {
        lightsOn.style.display = "none";
        lightsOff.style.display = "block";
    }
});

lightsOff.addEventListener("click", function(event){
    if (isInBorder(event)) {
        lightsOff.style.display = "none";
        lightsOn.style.display = "block";
    }
});
  • Related