Created
October 31, 2012 22:12
-
-
Save webaware/3990308 to your computer and use it in GitHub Desktop.
Make CSS drop-down menus work on touch devices
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.