ASA2k ASA2k - 4 months ago 9
HTML Question

How to make an Image display/hide using a button

I'm using the following code to make an image when a button is pressed:

<html>
<head>
<title>Image Display Test</title>
<script type="text/javascript">
<!--
function showImage(){
document.getElementById('loadingImage').style.visibility="visible";
}

-->
</script>
</head>
<body>
<input type="button" value="Show Button" onclick="showImage();"/>
<img id="loadingImage" src="pickups1.png" style="visibility:hidden"/>
</body>
</html>


So far it works, but then the image remains on the screen, Is there anyway to make it that if clicked again the image disappears?

Answer

You can check if image is visible and then hide/show it accordingly:

var elem = document.getElementById('loadingImage');
if (elem.style.visibility === 'visible') {
   elem.style.visibility = 'hidden';
} else {
   elem.style.visibility = 'visible';
}

or using shortcut (ternay operator):

var elem = document.getElementById('loadingImage');
elem.style.visibility = elem.style.visibility === 'visible' ? 'hidden' : 'visible';