I need help collapsing a collapsible div on page load.
I’m using this JavaScript code:
<script type="text/javascript">
function switchMenu(obj) {
var el = document.getElementById(obj);
if ( el.style.display != "none" ) {
el.style.display = 'none';
}
else {
el.style.display = '';
}
}
document.getElementById('aboutme').style.display = 'none';
</script>
to collapse HTML div id=”aboutme” when the <a ...>about me</a> is clicked:
<div class="container">
<a href="#" onclick="switchMenu('aboutme');">about me</a>
<div id="aboutme">
sample text to be expanded and collapsed
</div>
</div>
I can’t get the page to close my div#aboutme on page load.
I want this page to load with my div collapsed.
I thought that the JS line
document.getElementById('aboutme').style.display = 'none';
should do the trick but it doesn’t. What am I doing wrong?
Thanks for your help.
If you want your div to load collapsed, simply write the following
This should resolve the problem.
However, if you are still interested in the JavaScript solution keep reading.
As you said
I can't get the page to close my div#aboutme on page load– the problem is that you are not using “onload” event.Simply put the line
document.getElementById('aboutme').style.display = 'none';in your body’s onload attribute..something like this
and you should see the results with JavaScript. I recommend you use “style” method instead. much better.