Skip to content

Instantly share code, notes, and snippets.

@acusti
Last active July 11, 2017 18:00
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acusti/5420761 to your computer and use it in GitHub Desktop.
Save acusti/5420761 to your computer and use it in GitHub Desktop.
Plain vanilla JS with no dependencies to add touch device support for drop down menus (nested unordered list style). CSS selectors to display nested `<ul>` should look like: `body.no-touch ul.menu > li:hover > ul, ul.menu > li.tapped > ul { display: block; }`
(function(doc) {
// Add touch device support for dropdown menu
if (('addEventListener' in doc) && ('querySelectorAll' in doc) && (('ontouchstart' in window) || ('onmsgesturechange' in window))) {
var menu_item_selector = '.the-menu > div > ul > li',
menu_items = doc.querySelectorAll(menu_item_selector),
touchStart;
// Set up touch start handler
touchStart = function() {
if (this.className.indexOf(' tapped') > -1) {
this.className = this.className.replace(' tapped', '');
} else {
var els = doc.querySelectorAll(menu_item_selector + '.tapped');
for (var i = 0; i < els.length; i++) {
var el = els.item(i);
el.className = el.className.replace(' tapped', '');
}
this.className += ' tapped';
}
};
// Add handler to remove all .tapped classes when the user taps elsewhere (not on a menu)
// Check parent of evt.touches[0].target, because the target will be the span / anchor and the .tapped class gets added to the parent li
doc.addEventListener('touchstart', function(evt) {
if (evt.touches.length && evt.touches[0].target.parentElement.className.indexOf(' tapped') === -1) {
var els = doc.querySelectorAll(menu_item_selector + '.tapped');
for (var i = 0; i < els.length; i++) {
var el = els.item(i);
el.className = el.className.replace(' tapped', '');
}
}
}, false);
for (var i = 0, len = menu_items.length; i < len; i++) {
menu_items[i].addEventListener('touchstart', touchStart, false);
}
} else {
doc.body.className += ' no-touch';
}
})(document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment