Home > Javascript > Show and Hide DIV with Javascript

Show and Hide DIV with Javascript


Hi

try this example :-

<div id="anchor" onclick="FoldElement('content');">
 Click me to show the content!
</div>
<div id="content">
 <div id="content_inner">I am the content.</div>
</div>
//--- css

#anchor
{
 /* This element doesn't actually need any CSS.
  * You may add your style here.
  */
}

#content
{
 position: relative;
 display: block;
 overflow: hidden;
 /* Your CSS style here */
}

#content_inner
{
 position: relative;
 display: block;
 /* Your CSS style here */
}
//--- javascript

function FoldElement(contentId)
{
 var contentElement = element(contentId);
 if (contentElement.style.display == 'none')
 {
  TransitionShowNode(contentElement);
 }
 else if (contentElement.style.display == 'block'
  || !contentElement.style.display)
 {
  TransitionHideNode(contentElement);
 }
}

function TransitionHideNode(contentElement)
{
 SlideElement(contentElement.id, false);
}

function TransitionShowNode(contentElement)
{
 contentElement.style.display = 'block';
 SlideElement(contentElement.id, true);
}

function SlideElement(elementId, show)
{
 var slideSpeed = 10;
 var slideTimer = 10;

 var content = element(elementId);
 var content_inner = element(elementId + "_inner");
 var height = content.clientHeight;
 if (height == 0)
 {
  height = content.offsetHeight;
 }
 height = height + (show ? slideSpeed : -slideSpeed);

 var rerun = true;
 if (height >= content_inner.offsetHeight)
 {
  height = content_inner.offsetHeight;
  rerun = false;
 }
 else if (height <= 1)
 {
  height = 1;
  rerun = false;
 }

 content.style.height = height + 'px';
 var topPos = height - content_inner.offsetHeight;
 if (topPos > 0)
 {
  topPos = 0;
 }
 content_inner.style.top = topPos + 'px';

 if (rerun)
 {
  setTimeout("SlideElement('"
   + elementId + "', " + show + ");",
   slideTimer);
 }
 else
 {
  if (height <= 1)
  {
   content.style.display = 'none';
  }
 }
}

Good Luck

Advertisements
Categories: Javascript
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: