Forum Moderators: open

Message Too Old, No Replies

Show/hide 2 layers with onClick

onclick layers

         

admijn

8:21 pm on May 9, 2011 (gmt 0)

10+ Year Member



Hi all,

I want to open and close two div layers using this onClick script.

<script type="text/javascript">

function showhide(divid, state){
document.getElementById(divid).style.display=state
}
</script>


Then in my HTML I do the following (which isn't working):
<a href="#" onClick="showhide('testdiv1 , testdiv2' , 'block'); return false" >Show DIV</a> | <a href="#" onClick="showhide('testdiv1, testdiv2', 'none'); return false" >Hide DIV</a>


What does work is this:
<a href="#" onClick="showhide('testdiv1', 'block'); return false" >Show DIV</a> | <a href="#" onClick="showhide('testdiv1', 'none'); return false" >Hide DIV</a>


So a single layer works. It shows and hides as I intended it to do. But for two layers I need to rewrite this action apparently. Can anyone tell me where to start looking?

Thx for looking into this :)

rainborick

5:11 am on May 10, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Try:

<a href="#" onClick="showhide('testdiv1', 'block'); showhide('testdiv2', 'block'); return false" >Show DIV</a> | <a href="#" onClick="showhide('testdiv1', 'none'); showhide('testdiv2', 'none'); return false" >Hide DIV</a>

astupidname

7:29 am on May 10, 2011 (gmt 0)

10+ Year Member



Or, you could rewrite the function to take an unlimited number of element id's followed by the display state desired, such as:

//will take any number of string element id's as arguments,
//followed by the display state desired must be last string fed in
//EXAMPLE: showhide('elementOneId', 'elementTwoId', 'elementThreeId', 'block');
function showhide() {
var el,
i = 0,
a = arguments,
len = a.length - 1,
state = a[len];
while (i < len) {
el = document.getElementById(a[i++]);
if (el !== null) {
el.style.display = state;
}
}
}

If anybody's wondering, how to post formatted code on webmasterworld [webmasterworld.com]
Do not copy formatted code on webmasterworld from IE, use other browser such as Firefox.

admijn

11:04 am on May 10, 2011 (gmt 0)

10+ Year Member



Thx rainborick! This solution works and it's the fastest way for me to use right now. Live saver :)
astupidname, that's a very clean answer and I can use it for future projects thank you.