WEBDOOD.COM

Tag: gadgets

showOrHide algorithm

by webdood on Mar.01, 2010, under Javascript, Software Development

Making it easier for me to look up my own most useful block of code for displaying/hiding elements. This is the same bit of code I wrote for Microsoft that shipped with Vista and now Windows 7 with the Sidebar gadgets.

////////////////////////////////////////////////////////////////////////////////
//
// showOrHide([object|string] oHTMLElement, boolean bShowOrHide)
//           Shows or Hides an HTMLElement.
//           You can pass in the id to an object or the actual object
//
////////////////////////////////////////////////////////////////////////////////
function showOrHide(oHTMLElement, bShowOrHide) {
  try   {
    if (typeof(oHTMLElement)=="string")  {
      oHTMLElement = document.getElementById(oHTMLElement);
    }
    if (oHTMLElement && oHTMLElement.style) {
      if (bShowOrHide == 'inherit') {
        oHTMLElement.style.visibility = 'inherit';
      } else {
        if (bShowOrHide) {
          if (oHTMLElement.nodeName == 'TR') {
            oHTMLElement.style.visibility = 'inline-table';
          } else {
            oHTMLElement.style.visibility = 'visible';
          }
        } else {
          oHTMLElement.style.visibility = 'hidden';
        }
         try {
           if (bShowOrHide) {
             oHTMLElement.style.display = 'block';
           } else {
             oHTMLElement.style.display = 'none';
           }
         }
         catch (ex) {
         }
       }
     }
  }
  catch (ex) {
  }
}

Shannon Norrell

Now on GitHub

UPDATE TO THIS POSTING 4/14/2011
I have now taken to adding and removing a special className (usually called “hidden”) to oHTMLElements to show or hide them.

For example:

Assume in your CSS, there is a declaration like this:
.hidden { display:none; }

function showOrHide( oHTMLElement, bVisible ) {
  if (typeof(oHTMLElement)=="string")  {
    oHTMLElement = document.getElementById(oHTMLElement);
  }
  if (oHTMLElement) {
    if (!bVisible) {
      addClassName( oHTMLElement, 'hidden' );
    } else {
      removeClassName( oHTMLElement, 'hidden' );
  }
}

See our link about addClassName and removeClassName for more information on this technique.

Shannon Norrell

Leave a Comment :, , , more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Blogroll

A few highly recommended websites...

  • A List Apart
  • Dive into HTML5
  • Javascript: The Good Parts
  • QuirksMode.org