Sunday, February 19, 2012

Hiding A Dropdown Menu By Clicking Anywhere, jQuery

As I think I've mentioned before, my current project is an online company booklet, for the CESAC career fair. I've been working on drop down menus for it today, specifically the javascript code powering them.

In the past, I've created drop down menus with CSS only, because I hate relying on javascript. However, for touch screens, drop down menus must show on click, not on hover. For that, CSS won't do the trick.

Making a drop down menu with javascript is quite easy. You give the button and the menu similar classes, then create an if/else statement, where on click, the code checks to see if the menu is visible. If it is, it hides the menu. If it's already hidden, it shows the menu. The problem is, clicking elsewhere on the page does nothing. The only way to rehide the menu is to click on the button again.

To fix this, I put in a separate statement, saying, $(document).click, which checked to see if the menu was visible, and if so, hides it. The problem is, it runs after the button click statement. So if the menu is visible and you click on a random part of the page, it hides it. If it's visible, and you click on the button (which is still part of the document), both statements hide it, still okay. If it's hidden though, and you click the button, the button statement shows it, then the full document statement hides it. Since it starts out hidden, you can never see it.

After an hour of research and trying things, I figured out how to fix it. The key is in order of operations. You want the full document check to happen first. That way if you click on the button, the button statement will happen AFTER the full document statement, and remain in control.

The javascript we need is window.setTimeout(function(){ }, 1);

You place that around the action that shows the variable, in the button statement. For me, it ended up being window.setTimeout(function(){ $(child_id).show(); }, 1); This delays showing the menu until after the document click statement checks to see if it's visible, and so doesn't hide it if not needed. And works.
 

No comments:

Post a Comment