Home > Enterprise >  how to show image on click, and hide it again when clicking again
how to show image on click, and hide it again when clicking again

Time:04-02

I want to when I click on a sentence or a button an image appears, and when I click it again it disappears. but my code doesn't seem to work using JS and HTML.

let pic = document.getElementById(hiddenclickimg);
let word = document.getElementById(hiddenclick);

function showPic(){
  pic.hidden = 'false' ;
  word.style.color = 'red';
  word.style.backgroundColor = 'blue';
}


word.onclick = showPic;
<h3 id="Work">Work Experience</h3>
      <div >
        <ul>
          <li>
            <img
              src="./Images/Alex Sydney.jpg"
              alt="alex sydney"
              id="hiddenclickimg"
              hidden="true"
            />
            <button id="hiddenclick">Alex Sydney Hospital</button>
          </li>
        </ul>
      </div>

<script src="./main.js"></script>

CodePudding user response:

You can use the onclick of a button and toggle a class that hides the image when it has that class.

HTML:

<button onclick="imageClick()">Toggle Image</button>

CSS:

.hidden {
  opacity: 0;
}

Javascript:

const image = document.getElementById('hiddenclickimg');

const imageClick = () => {
   image.classList.toggle('hidden');
}

There are different CSS properties you could use to hide the image, but opacity is a good basic one.

CodePudding user response:

You don't need to set 2 ids to do the trick using css property display none.

For example you want to hide that image:

<img id="dog_image" src="dog.png" alt="Rex the Labradoodle" >

function hideDog() {
  const dog = document.getElementById("dog_image");
  if (dog.style.display === "none") {
    dog.style.display = "block";
  } else {
    dog.style.display = "none";
  }
}

And then just set the button:

<button onclick="hideDog()">Hide/Show my dog</button>

CodePudding user response:

you can use flag to change state of the image like following

let  imagehidden =false
let pic = document.getElementById('hiddenclickimg');
let word = document.getElementById('hiddenclick');

function showPic(){
if(imagehidden){
  pic.hidden = false ;
  word.style.color = 'red';
  word.style.backgroundColor = 'blue';
  imagehidden=false
  }
  else{
   pic.hidden =true;
   imagehidden=true
  }
}

  • Related