While trying to make a basic collapsing div
with Javascript, I came across the following odd bug; with this code:
<html>
<head>
<style type="text/css">
.hidden
{
display: none;
}
</style>
<script type="text/javascript">
function toggle()
{
var element = document.getElementById('hidden1');
if(element.style.display === 'none')
{
element.style.display = 'inline';
}
else
{
element.style.display = 'none';
}
}
</script>
</head>
<body>
<a onclick="toggle()">Click me</a><br />
<div id="hidden1" class="hidden">
stuffs
</div>
</body>
</html>
I had expected it to work as it would appear: the div
would start hidden, and upon every click it would go from visible to invisible, however it does not: it requires 2 clicks to show the element the first time, and after some debugging I realised that the div
seems to be in some weird quantuum flux. When adding the following alert to the top of the toggle()
method:
alert('\'' + document.getElementById('hidden1').style.display + '\'');
I'm given ''
, meaning it's empty. However when I do this in exactly the same place:
console.log(document.getElementById('hidden1').style);
The console then shows:
[object CSS2Properties]
With the following properties:
0: "display"
...
display: "none"
However, when the CSS declaration for .hidden
is moved inline to the div
's style
, the code works exactly as one would expect. Does anyone know why this is happening?
I'd also like to know if anyone can't reproduce the problem, as I've experienced it with apache on both Centos and Windows, and with Firefox 24, Chrome 30 and the latest Opera browsers.