2 Replies - 20394 Views - Last Post: 26 June 2011 - 11:01 AM

#1 sunjava1  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 35
  • Joined: 14-May 11

How to hide and show multiple divs using javascript

Posted 26 June 2011 - 09:35 AM

I want to hide and show a div using javascript, but the problem is, Here is my code, but it only execute only the top condition i.e the first one,
here is the code :-


<head>
<script>
function showOrhide()
{

if(document.getElementById("firstBtn"))
{

document.getElementById('divNo1').style.display="block";
document.getElementById('divNo2').style.display="none";
return false;
}
else if(document.getElementById("secondBtn"))
{

document.getElementById('divNo1').style.display="none";
document.getElementById('divNo2').style.display="block";
return false;
}


}

</script>
</head>
<body>

<div id="firstBtn"><a href="" onclick="return showOrhide()"> Sample text 1 </a></div>

<div id="secondBtn"><a href="" onclick="return showOrhide()"> Sample text 2 </a></div>

<div id="divNo1" style="display:none;"> Hello </div>

<div id="divNo2" style="display:none;"> Hi </div>
</body>



Is This A Good Question/Topic? 0
  • +

Replies To: How to hide and show multiple divs using javascript

#2 codeprada  Icon User is offline

  • Changed Man With Different Priorities
  • member icon

Reputation: 948
  • View blog
  • Posts: 2,357
  • Joined: 15-February 11

Re: How to hide and show multiple divs using javascript

Posted 26 June 2011 - 10:32 AM

Your code only hides the DIV. You don't need to check if the button was clicked either since for the function to be called the button must be clicked in the first place.
If you want to however check which button is clicked take a look at this script
<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">
			function alertName(a)
			{
				alert(a.id);
			}
        </script>
    </head>
    <body>
        <a onclick="alertName(this)" id="button1">Button1</a>
        <a onclick="alertName(this)" id="button2">Button2</a>
    </body>
</html>



You can get the id of which link that's calling the function by simply passing the element to the function. In turn this will help you determine which DIV's to hide or show.
Hint
switch(a.id)
{
	case 'button1':
		//do whatever
		break;
	case 'button2':
		//do whatever
		break;
}

Was This Post Helpful? 0
  • +
  • -

#3 sunjava1  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 35
  • Joined: 14-May 11

Re: How to hide and show multiple divs using javascript

Posted 26 June 2011 - 11:01 AM

Thanks, done :)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1