I want to toggle the image using if-else
but it didn't work, can someone please explain what is wrong with the code.
<img src="img/somepic.jpg" id="pic"><br/>
<a href="javascript:toggleImg()">Toggle Image</a>
<script>
function toggleImg(){
var img = document.getElementById('pic');
var checkForVisible = img.style.visibility == "visible";
if(checkForVisible == "visible"){
img.style.visibility = "hidden";
}
else{
img.style.visibility = "visible";
}
}
</script>
I tried using "ternary operator"
img.style.visibility = checkForVisible ? "hidden" : "visible";
and it worked. I just want to know about the "if-else" code which doesn't work. Thanks
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";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With