Forum Moderators: open

Message Too Old, No Replies

Javascript/CSS function mess

         

wavesurf

6:17 pm on Jul 12, 2006 (gmt 0)

10+ Year Member



Hi -

Trying to control a number of different divs on/off on a page by having a function that takes it arguments from a open/close function, but I don't seem to get it to work. Anyone know what I'm doing wrong?

function open(variable) {
document.getElementById(variable).style.display="block"
}

function close(variable) {
document.getElementById(variable).style.display="none"
}

<div id="test1">
content1
</div>

<div id="test2">
content2
</div>

<a href="javascript:open(test1);">Open 1</a>
<a href="javascript:open(test2);">Open 2</a>
<a href="javascript:close(test1);">Close 1</a>
<a href="javascript:close(test2);">Close 2</a>

If I make a function for each div it seems to work, but when I try it with the "variable" it doesn't. Any ideas?

Thanks for all help.

kaled

7:37 pm on Jul 12, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



In this case, you need quotes when calling the function.

<a href="javascript:open('test1');">Open 1</a>

In this case, test1 is an identifier name not a variable.

Your open function would be better written

function open(id) {
id = document.getElementById(id);
if (id) id.style.display="block";
}

Kaled.

wavesurf

7:59 pm on Jul 12, 2006 (gmt 0)

10+ Year Member



Thanks a bunch. I actually just got it sorted on my own. Figured out the little apostrophe error after pulling my hair for a while. But thanks anyway.

However. Could you please explaing why that way of coding would be better than how I did it? What are the bonuses?

Thanks again.

birdbrain

8:13 pm on Jul 12, 2006 (gmt 0)



Hi there wavesurf,

you may be interested in this example...


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<style type="text/css">
<!--
a {
color:#000;
text-decoration:none;
background-color:#fff;
}
.hide {
display:none;
}
.show {
display:block;
}
-->
</style>

<script type="text/javascript">
<!--
window.onload=function() {
anc=document.getElementsByTagName('a');
for(c=0;c<anc.length;c++) {
anc[c].onclick=function() {
n=this.id.split('a')[1];
this.innerHTML=(this.innerHTML=='close '+n)?'open '+n:'close '+n;
obj=document.getElementById('test'+n);
obj.className=(obj.className=='hide')?'show':'hide';
return false;
}
}
}
//-->
</script>

</head>
<body>

<ul>
<li><a id="a1" href="#">close 1</a></li>
<li><a id="a2" href="#">close 2</a></li>
<li><a id="a3" href="#">close 3</a></li>
<li><a id="a4" href="#">close 4</a></li>
</ul>

<div id="test1">this is content 1</div>
<div id="test2">this is content 2</div>
<div id="test3">this is content 3</div>
<div id="test4">this is content 4</div>

</body>
</html>

birdbrain