...

View Full Version : Can't read css visibility value



toddmanning
05-16-2012, 08:34 PM
I'm not sure why this code executes the first if condition. What should I be doing instead?

<!DOCTYPE html>
<head>

<style>
#test { visibility:hidden; }
</style>

<script type="text/javascript">

function read(ID)
{
if(document.getElementById(ID).style.visibility == '') alert("why does this pop up?");
else if(document.getElementById(ID).style.visibility == 'hidden') alert("this is what I would expect");
else alert("never reached");
}
</script>


</head>
<body>
<form><input type="button" value="test" onclick="read('test');"">
<p id='test'> testing visibility</p>
</body>
</html>

xelawho
05-16-2012, 08:42 PM
javascript cannot read css values unless they are defined inline or by the javascript. I don't know why. It's annoying. There are a couple of ways around it, probably simplest here being to define the style inline:


<!DOCTYPE html>
<head>

<style>
</style>

<script type="text/javascript">

function read(ID)
{
if(document.getElementById(ID).style.visibility == '') {alert("why does this pop up?");}
else if(document.getElementById(ID).style.visibility == 'hidden') {alert("this is what I would expect");}
else {alert("never reached");}
}
</script>


</head>
<body>
<form><input type="button" value="test" onclick="read('test');"">
<p id='test' style="visibility:hidden;" > testing visibility</p>
</body>
</html>

Old Pedant
05-16-2012, 08:54 PM
What most people do, when they need to flip-flop between two states (e.g, in your case, presumably between hidden and visible) is to look for the NON-DEFAULT state.

So if the CSS default is, as in your case, hidden, then in the JS code you would do something like this:


var para = document.getElementById("test");
para.stye.visibility = ( para.stye.visibility == "visible" ? "hidden" : "visible" );

This works because the default is seen as just "" so the first flip-flop changes it to "visible" and from then on the value has been set by JS code and so is available.

Clearly, if you don't know ahead of time which is the default, then this can't work.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum