MattsBits
MattsBits - Brunel District

MattsBits

MattsBits RSS Feed - Subscribe Now!

12/06/2009 : Set The Visibility Of HTML Items By Name

Categories : | JavaScript | Views : 334 | Email Link Print

The following JavaScript function allows you to set the visibility of an HTML element to be visible or invisible. 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 name attribute value and the mode you wish to use.

<script language="JavaScript">
<!-- Begin
function toggleByName(sName,sMode)
{
// This function shows/hides or toggles the
// visibility of all elements with their
// name attribute set to sName
//
// mode 0 - Hide
// mode 1 - Show
// mode 2 - Toggle
//
// http://www.mattsbits.co.uk

var elements = document.getElementsByName(sName);
var i=0;
        
  // For each item with name sName
  for (i=0;i<elements.length;i++)
  {
    switch (sMode) {
    case 0:
      // Hide
      elements[i].style.display='none';    
      break;
    case 1:
      // Show
      elements[i].style.display='block';    
      break;
    case 2:
      // Toggle
      if (elements[i].style.display=='none') {
        elements[i].style.display='block'; 
      } else {
        elements[i].style.display='none'; 
      }  
      break;   
    }
  }
}
//  End -->
</script>


Many elements can share the same name value and this function will affect all of them.

Technorati Tags : | javascript |

Author : Matt Hawkins  Last Edited By : Matt Hawkins  Permalink : Set The Visibility Of HTML Items By Name
 
 
 
PHP Powered  MySQL Powered  Valid XHTML 1.0  Valid CSS  Firefox - Take Back The Web  EUKHost - Recommended Webhosting Solutions

MattHawkins CMS v2.0 - Copyright 2009-2010