Question

http://jsfiddle.net/xNnQ5/

I am trying to use JavaScript (and HTML) to create a collapsible menu (c_menu) for my website. I would like it to be opened when the user clicks on the div menu_open, and to close when the user clicks menu_close. However, when I load the page, all that happens is the menu simply scrolls up, as if I have clicked menu_close, which I haven't. What should I do?


Code:


index.html (Only a snippet)

<style type = "text/css">
#c_menu {
position: absolute;
width: 435px;
height: 250px;
z-index: 2;
left: 6px;
top: 294px;
background-color: #0099CC;
margin: auto;
</style>

<div id="menu_open"><img src="images/open.jpg" width="200" height="88" /></div>
<input type="button" name="menu_close" id="menu_close" value="Close"/>
<div id="c_menu"></div>

<script type = "text/javascript" src = "menu.js"> </script>

menu.js (Full code)

document.getElementById("c_menu").style.height = "0px";
document.getElementById("menu_open").onclick = menu_view(true);
document.getElementById("menu_close").onclick = menu_view(false);

function menu_view(toggle)
{
  if(toggle == true)
  {
      document.getElementById("c_menu").style.height = "0px";
      changeheight(5, 250, 0);
  }
  if(toggle == false)
  {
      document.getElementById("c_menu").height = "250px";
      changeheight(-5, 0, 250);
  }
}

function changeheight(incr, maxheight, init)
{
  setTimeout(function () {  
  var total = init; 
  total += incr; 
  var h = total + "px";
  document.getElementById("c_menu").style.height = h;                             
  if (total != maxheight) {            
     changeheight(incr, maxheight, total);            
  }                        
}, 5)
}
Was it helpful?

Solution

Try this:

document.getElementById("menu_open").onclick = function() {menu_view(true)};
document.getElementById("menu_close").onclick = function() {menu_view(false)};

When you define the function with a parenthesis ( ...onclick = menu_view(true) ), the function is called automatically.

When you have a function with no parameters, you can use it like you did, but without the parenthesis:

document.getElementById("menu_open").onclick = menu_view;
document.getElementById("menu_close").onclick = menu_view;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top