skip to Main Content

I want to show a picture on when I click a button(on)and when I click button (off) will hide picture on and display picture off

I have this code the javascript runs in button(on)show picture on and button(off) hide picture on
so I need to show picture off when click button off and hide when click button on.

 <button id="show-image-button"  style="--clr:#0FF0FC"><span>on</span><i></i></button>
  <br>
  <button  onclick="myFunction()"  style="--clr:#0FF0FC"><span>off</span><i></i></button>
  <br>
  <img id="my-image"  src="pump on.gif" alt="anim" style=" text-align: center;  justify-content:center;display: none;width:130px;height:130px;">
  <br>
  <img  src="pump off.png" alt="anima" style="display: none;width:120px;height:100px;">
  <br>
  
    <script>
   
    function myFunction() {
        document.getElementById("my-image").style.visibility = "hidden";
      
        
      }
      const showImageButton = document.getElementById("show-image-button");
      const myImage = document.getElementById("my-image"); 
      showImageButton.addEventListener("click", () => { 
         myImage.style.display = "block"; 
  
      }
      );
   
    </script>
 

2

Answers


  1. hi try to use the if statement and then use the test function on your button you can both the arrow function or the regular function method

    let show = true  
    let test = () => {
       if (show == true) {
         document.getElementById("sth").style.display = "none"
          show = false
        } 
     else {
         document.getElementById("sth").style.display = "block"
          show = true
        }
    }
    <img id="sth" src="something"/>
    Login or Signup to reply.
  2. Simplified function approach

    function myFunction(val) {
         
         const imgHolder = document.getElementById("my-image");
         const images = {
              off : "pump off.png", 
              on: "pump on.png"
         }
    
    
       if(!val) { imgHolder.classList.add('d-none'); return };
        
         imgHolder.classList.remove('d-none')
         imgHolder.setAttribute('src', images[val])
         imgHolder.setAttribute('alt', images[val]) // Optional
     
     }
    .d-none { display: none; }
    <button onclick="myFunction('on')">
      <span>on</span>
    </button>
    <br />
    <button onclick="myFunction('off')">
       <span>off</span>
    </button>
    
    <br />
    
    <img id="my-image" src="pump on.gif" alt="anim ON" class="d-none" />
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search