MattsBits
MattsBits

MattsBits

Set The Visibility Of HTML Items By ID  

by Matt Hawkins, 12/06/2009
Categories : JavaScript

The following JavaScript function allows you to set the visibility of an HTML element to be visible or invisible by the value of its ID attribute. It also allow you to toggle the current visibility.

This function is a useful way of showing and hiding html items including divs and images.

The function definition is shown below. It takes two arguments : The Id attribute value and the mode you wish to use.

<script type="text/javascript">
<!--
function toggleById(sId,sMode)
{
// This function shows/hides or toggles the
// visibility of all elements with their
// id attribute set to sId
//
// mode 0 - Hide
// mode 1 - Show
// mode 2 - Toggle
//
// http://www.mattsbits.co.uk

var element = document.getElementById(sId);

  switch (sMode) {
  case 0:
    // Hide
    element[i].style.display='none';    
    break;
  case 1:
    // Show
    element[i].style.display='block';    
    break;
  case 2:
    // Toggle
    if (element[i].style.display=='none') {
      element[i].style.display='block'; 
    } else {
      element[i].style.display='none'; 
    }  
    break;   
  }
}
//  End -->
</script>


Id values must be unique so this function only attempts to change the visibility of one element.

Author : Matt Hawkins  Last Edit By : Matt Hawkins
PHP Powered  MySQL Powered  Valid XHTML 1.0  Valid CSS  Firefox - Take Back The Web  EUKHost - Recommended Webhosting Solutions

MattHawkins CMS v3.0 - Copyright 2009-2017