Skip to content

Instantly share code, notes, and snippets.

@webaware
Created October 31, 2012 22:12
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save webaware/3990308 to your computer and use it in GitHub Desktop.
Save webaware/3990308 to your computer and use it in GitHub Desktop.
Make CSS drop-down menus work on touch devices
// code from blog post:
// http://snippets.webaware.com.au/snippets/make-css-drop-down-menus-work-on-touch-devices/
// this version: 27 November, 2012
// "an attempt to make it work on Windows 8 -- please try and tell me"
// see whether device supports touch events (a bit simplistic, but...)
var hasTouch = ("ontouchstart" in window || ("msMaxTouchPoints" in navigator && navigator.msMaxTouchPoints > 0));
var iOS5 = /iPad|iPod|iPhone/.test(navigator.platform) && "matchMedia" in window;
// hook touch events for drop-down menus
// NB: if has touch events, then has standards event handling too
// but we don't want to run this code on iOS5+
if (hasTouch && document.querySelectorAll && !iOS5) {
var i, len, element,
touchEvent = window.navigator.msPointerEnabled ? "MSPointerDown" : "touchstart",
dropdowns = document.querySelectorAll("#menu li.children > a");
function menuTouch(event) {
console.log("menuTouch called");
// toggle flag for preventing click for this link
var i, len, noclick = !(this.dataNoclick);
// reset flag on all links
for (i = 0, len = dropdowns.length; i < len; ++i) {
dropdowns[i].dataNoclick = false;
}
// set new flag value and focus on dropdown menu
this.dataNoclick = noclick;
this.focus();
}
function menuClick(event) {
console.log("menuClick called");
// if click isn't wanted, prevent it
if (this.dataNoclick) {
console.log("click prevented");
event.preventDefault();
}
}
for (i = 0, len = dropdowns.length; i < len; ++i) {
element = dropdowns[i];
element.dataNoclick = false;
element.addEventListener(touchEvent, menuTouch, false);
element.addEventListener("click", menuClick, false);
}
}
@timbeadle
Copy link

This is ace, but it doesn't work if you close the menu by tapping somewhere else on the page, then tap the same menu item again.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment