PDA

View Full Version : How to toggle 1 element on and the other off simultaneously.



green
06-28-2007, 06:07 AM
I've been using this script for toggling elements on and off.

<script type="text/javascript">
<!--
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'none')
e.style.display = 'block';
else
e.style.display = 'none';
}
//-->
</script>

BUT, I have TWO elements; 1 visible and 1 invisible and I'd like the following:

onClick from one single link eg.<a href>: element 1 becomes visible and element 2 becomes INvisible at the same time. onClick again element 2 becomes visible and element 1 becomes INvisible etc. ie. only one element visible at any one time.

Any ideas greatly appreciated.:cool:

jscheuer1
06-28-2007, 03:48 PM
This is not an endorsement or criticism of your existing code which I have used in only slightly modified form (comments within script blocks are not useful, but not really harmful for this type of script). Here it is doing just what I think you asked:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'none')
e.style.display = 'block';
else
e.style.display = 'none';
}
</script>
</head>
<body>
<div id="el1">Hi</div>
<div id="el2" style="display:none;">Bye</div>
<a href="javascript:toggle();" onclick="toggle_visibility('el1');toggle_visibility('el2');return false;">Toggle</a>
</body>
</html>

Note: The href is just a throwaway href and could be anything, just not nothing, unless it isn't there at all (having no href attribute would be fine). Having it this way gives the user a clue as to what clicking will do.

green
06-28-2007, 06:57 PM
That works just about perfect. Thank you again, John.