Skip to content Skip to sidebar Skip to footer

Image Visibility Using Javascript

I want to toggle the image using if-else but it didn't work, can someone please explain what is wrong with the code.

Solution 1:

Solution 2:

Use toggle instead of if else.

functiontoggleImg() {
  var img = document.getElementById('pic');
  img.classList.toggle('hidden');

}
.visible {
  display: block;
}
.hidden {
  display: none;
}
<imgsrc="img/somepic.jpg"id="pic"><br/><ahref="javascript:toggleImg()">Toggle Image</a>

Solution 3:

There are mistakes. For example in the checkForVisible var. I'n not sure what you're trying to do but there are too many equals. You can try this out:

functiontoggleImg(){
    var img = document.getElementById('pic');

    img.style.visibility = "visible";

    if(img.style.visibility === "visible"){
        img.style.visibility = "hidden";
    }
    else{
        img.style.visibility = "visible";
    }

}

Post a Comment for "Image Visibility Using Javascript"