Toggle Visibility Javascript

Are you looking for a way to toggele the visibility of an element using Javascript? The short javascript tutorial below will teach you how to create this function of hiding and then showing an element.

<script type="text/javascript">
 function ToggleVisibility(image, element){
 var image = document.getElementById(image)
 var element = document.getElementById(element)
 if (element.style.display == "none") {
   element.style.display = "block"
   image.src = "open.png"
 }
 else{
   element.style.display = "none"
   image.src = "close.png"
 }
 }
</script>

 

The function above requires two parameters. The first one is the name of the close/open image. The second parameter is the name of the element we want to hide or show. The function checks the state of the element, and changes the state. In other words, the function shows a hidden section and hides a displayed section, thanks to the if/else conditional statement. The function also changes the image source for the item we are planning to click on. The open.png and close.png files could either be arrows or plus/minus signs.

In order for the  javascript code above to actually do something we need to have the appropriate HTML code as seen below. The <img> element will perform the toggling on your web page, while the div is the actual element that needs to be either hidden or displayed. It is very important that these two elements are given unique ids, in our case myimage1 and mydiv1; otherwise the javascript Toggle Visibility function will not work properly.

 

<img src="open.png" id="myimage1" onclick="ToggleVisibility('myimage1','mydiv1')">
<div id="mydiv1">
 <p>
 This is the paragraph that will be hidden or displayed when we click the image.
 </p> 
</div>

Leave comment

Your email address will not be published. Required fields are marked *