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:
You do this:
var checkForVisible = img.style.visibility == "visible";
The == "visible" makes it the result of the equals expression so it's going to be true or false.
Your if/else is checkForVisible == "visible" which won't work because is will only be true or false. You only need to compare once.
if(img.style.visibility == "visible"){
        img.style.visibility = "hidden";
    }
    else{
        img.style.visibility = "visible";
    }
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"