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
checkForVisibleis a boolean, you're comparing it to"visible"again for some reason. Just useif(checkForVisible).if(checkForVisible == "visible") {to see what value the var checkForVisible holds. Learning how to do this will allow you to debug these problems yourself in future.