Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save besimhu/a392e0b7e9eb4bf6ee33 to your computer and use it in GitHub Desktop.
Save besimhu/a392e0b7e9eb4bf6ee33 to your computer and use it in GitHub Desktop.
Toggle navigation, hide navigation on scroll, and close navigation if clicked outside of navigation.
module.exports = function() {
require('./setupMqSync')();
var $root = $('body'),
$header = $root.find('.main-header'),
$nav = $root.find('.nav-primary'),
$menu_toggle = $header.find('.menu-trigger'),
$active_class = 'nav-open',
prevent_default = function(e) {
e = e || window.event;
if (e.preventDefault)
e.preventDefault();
e.returnValue = false;
},
close_nav = function() {
$root.removeClass($active_class);
},
toggle_nav = function() {
if ($root.hasClass($active_class)) {
$root.removeClass($active_class);
} else {
$root.addClass($active_class);
}
},
disable_scroll = function() {
$root.bind('touchmove', function(e){
e.preventDefault();
});
},
enable_scroll = function() {
$root.unbind('touchmove');
};
// Toggle navigation and handle showing through CSS.
$menu_toggle.on('click touch', function() {
toggle_nav();
// Disable touch scrolling if navigation is open on mobile.
if ( $.mqSync.isBelow('mq-small') && $root.hasClass($active_class) ) {
disable_scroll();
} else {
enable_scroll();
}
});
if ( $.mqSync.isBelow('mq-small') ) {
// Close menu when scrolling.
var didScroll = false;
$(window).scroll(function() {
didScroll = true;
});
setInterval(function() {
if (didScroll) {
didScroll = false;
close_nav();
}
}, 100);
}
// Close menu if user clicks anywhere else on the page.
$(document).on('click touchstart', function(e) {
if ($root.hasClass($active_class) && $(e.target).closest('.main-header').length === 0) {
close_nav();
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment