0

I have a dropdown menu on a web page that I created using CSS. It drops down sub menus when hovering over items. It works great on my PC, but on a touchscreen I can't get the menu to close when clicking outside the menu. I can't find a way for the touchscreen to recognize that I am not clicking on the menu anymore.

So basically I need a trigger to be fired to tell the menu to close when I touch the screen anywhere outside the menu.

I would image that I need some sort of Javascript or JQuery trigger. I don't know how this could be done simply with CSS.

I can include the CSS for the menu if you want to see it, but that just creates the menu. I need something that closes the menu and that is not in the CSS.

EDIT:

So far this is the only thing that works, but how can I tell it to ignore the touch if it is on the menu?

$(document).bind('touchstart', function(event) {
      event.preventDefault();                  
      var target = event.target;
      target = $(this);
      alert("touched");
    });

HTML

<div id="menu">
  <ul id="nav">
    <li class="taphover"><a href="#">Tools</a>
      <ul>
        <li><a href="#">Change Password</a></li>
      </ul>
    </li>    
John
  • 1,310
  • 3
  • 32
  • 58
  • http://stackoverflow.com/questions/6463486/jquery-drop-down-menu-closing-by-clicking-outside?rq=1 – ckersch Jun 13 '14 at 14:42
  • @ckersch Actually there is a "better" way (than the accepted answer in your link) to deal with this issue. Here is an article covering this topic: http://css-tricks.com/dangers-stopping-event-propagation/ – mrksbnch Jun 13 '14 at 14:53
  • If possible, can post `html`, `css`, `js` ? Tried jquery `.on("touchmove", fn)` ? See https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Touch_events – guest271314 Jun 13 '14 at 15:02
  • @demrks Your link works on PC, but again, not on iPad. If I touch anywhere on the body, the dropdown menu does not close. – John Jun 13 '14 at 15:06
  • Do the exact same thing that all of these examples are suggesting, but use the `touchstart` event instead of `click`. – ckersch Jun 13 '14 at 22:24
  • possible duplicate of [How to detect a click outside an element?](http://stackoverflow.com/questions/152975/how-to-detect-a-click-outside-an-element) – vsync May 31 '15 at 08:23

1 Answers1

0

A fairly common way to close something when you click outside of it is to attach a click handler to the body. When that event is fired you check to see if it is not your dropdown and then hide/close it.

Example

$('body').click(function() {
   // Check here is dropdown and close if not
});
Colin Bacon
  • 15,436
  • 7
  • 52
  • 72
  • The problem with this is getting the click to fire on mobile and not instigating a page zoom or pan gesture. I would have the parent menu toggle submenu visibility on the 'click' event instead. – woodscreative Jun 13 '14 at 14:46
  • Thanks Colin, but the mobile device (iPad) doesn't recognize the body.click event. – John Jun 13 '14 at 14:48