Trying to toggle the visibility of an element with JavaScript. It's working, but I have to click once first, which of course isn't optimal. Can someone point out to me why this isn't working properly?
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
#foo {
display: block;
}
<a href="#" onclick="toggle_visibility('foo');">Click here to toggle visibility of element #foo</a>
<div id="foo">This is foo</div>
Trying to toggle the visibility of an element with JavaScript. It's working, but I have to click once first, which of course isn't optimal. Can someone point out to me why this isn't working properly?
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
#foo {
display: block;
}
<a href="#" onclick="toggle_visibility('foo');">Click here to toggle visibility of element #foo</a>
<div id="foo">This is foo</div>
Share
Improve this question
asked Dec 4, 2015 at 21:17
Garland BriggsGarland Briggs
1192 silver badges13 bronze badges
3
- #foo { display: none; } – user2417483 Commented Dec 4, 2015 at 21:19
- So you want #foo to be invisible when you load the page? – redeagle47 Commented Dec 4, 2015 at 21:27
- No, not necessarily. Rick Hitchcock pointed me in the right direction. – Garland Briggs Commented Dec 4, 2015 at 22:57
1 Answer
Reset to default 9Reverse your if
and else
tests. JavaScript can't read CSS properties from style
unless it explicitly sets them:
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'none')
e.style.display = 'block';
else
e.style.display = 'none';
}
#foo {
display: block;
}
<a href="#" onclick="toggle_visibility('foo');">Click here to toggle visibility of element #foo</a>
<div id="foo">This is foo</div>