skip to Main Content
function yourFunction() {
   let displayImage = document.getElementById('imahe')
   if(displayImage.src.match('images/cabato.jpg')){
    displayImage.src = 'images/nin.jpg'
   }
   else {
    displayImage.src = 'images/cabato.jpg'
   }
    }

Im using simple if/else, need to know how to still make this work by using global boolean variable

3

Answers


  1. There’s no need for a variable at all. You can use a simple ternary operator to solve this for a toggle operation.

    const imgEl = document.querySelector("img");
    
    // Set up a click event handler
    document.querySelector("button").addEventListener("click", function(event){
      // A simple ternary operator that checks the current image
      // source and sets it according takes care of this.
      imgEl.src = imgEl.src.includes("happy-smiley-emoticon-face-vector.jpg") ? "https://image.shutterstock.com/image-vector/smile-icon-vector-face-emoticon-260nw-1721368459.jpg"  : "https://static.vecteezy.com/system/resources/thumbnails/008/734/498/small/happy-smiley-emoticon-face-vector.jpg"
    });
    img { width: 50px; }
    <button type="button">Toggle</button>
    <img src="https://static.vecteezy.com/system/resources/thumbnails/008/734/498/small/happy-smiley-emoticon-face-vector.jpg">
    Login or Signup to reply.
  2. One way is state variable flag and toggle on button click and re-render image.

    let flag = true;
    const url1 = "https://www.kasandbox.org/programming-images/avatars/leaf-blue.png"
    const url2 = "https://www.kasandbox.org/programming-images/avatars/leaf-green.png"
    
    function renderImage() {
      const img = document.querySelector("#pic");
      img.src = flag ? url1 : url2;
    }
    
    document.querySelector("#toggle").addEventListener("click", function () {
      flag = !flag;
      renderImage()
    });
    <img id="pic" src="https://www.kasandbox.org/programming-images/avatars/leaf-blue.png">
    
    <button id="toggle"> toggle </button>
    Login or Signup to reply.
  3. I post you a code snippet easy to understand and to modify less.

    let isImageDisplayed = true;
    function yourFunction() {
       let displayImage = document.getElementById('imahe')
       if (isImageDisplayed) {
          displayImage.src = 'images/nin.jpg'
       } else {
          displayImage.src = 'images/cabato.jpg'
       }
       isImageDisplayed = !isImageDisplayed
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search