Forum Moderators: open

Message Too Old, No Replies

Open a div block and to close the others

         

romzinho2k7

2:29 pm on Jun 2, 2007 (gmt 0)

10+ Year Member



Hey friends,

I want to do a system with some divs hidden and another to click and to open these that are hidden.

It follows the code:

script:

<script type="text/javascript">
function Open(id)
{
var style = document.getElementById(id).style;

if(style.display == "none")
{
style.display = "block";
}
else
{
style.display = "none";
}
}
</script>

divs:

<div id="all">
<div style="background:#eee; width:150px; cursor:pointer;" onclick="Open('1');">DIV 1</div>
<div id="1" style="display:none;">Div 1</div>
-------------------------
<div style="background:#eee; width:150px; cursor:pointer;" onclick="Open('2');">DIV 2</div>
<div id="2" style="display:none;">Div 2</div>
</div>

What I want, it is to make when a person opens one of these divs, all the others that are opened, close.

In the example, all divs can be opened at the same time. And is not that that I want.

In other words, when someone clicks in the DIV 1, want DIV 2 closes.

Does anybody know how can that?

Sorry my english, I did not yet learn

rocknbil

6:56 pm on Jun 2, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Some recommendations:
- Don't ID an object beginning with a number
- A link can be set to display:block, use a link for clickables
- "Open" is a command to open a window, use another name
- assigning a var named "style" may confuse browsers (but it may not, changed just in case)
- "all" will probably confuse IE, see document.all

Here's one way.


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<!-- previous on one line -->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>div-open-close</title>
<style type="text/css">
.gray { background-color:#eee; display: block; padding: 6px; width:150px; cursor:pointer; }
</style>
<script type="text/javascript">
function OpenDiv(id) {
for (i=1;i<=2;i++) { // so you can add more than 2
var divname = 'div'+i;
var divStyle = document.getElementById(divname).style;
divStyle.display=(id==divname)?'block':'none';
}
}
</script>
</head>
<body>
<div id="alldivs"> <!-- all will probably confuse IE = see document.all -->
<a class="gray" onclick="OpenDiv('div1');">DIV 1</a>
<div id="div1" style="display:none;">Div 1</div>
<a class="gray" onclick="OpenDiv('div2');">DIV 2</a>
<div id="div2" style="display:none;">Div 2</div>
</div>
</body>
</html>

romzinho2k7

3:44 pm on Jun 4, 2007 (gmt 0)

10+ Year Member



Thank you very much.