Skip to content

Instantly share code, notes, and snippets.

@harisrozak
Last active October 14, 2016 04:33
Show Gist options
  • Save harisrozak/5fc9e9b32f771bb113124711fba90932 to your computer and use it in GitHub Desktop.
Save harisrozak/5fc9e9b32f771bb113124711fba90932 to your computer and use it in GitHub Desktop.
jQuery detect header scroll, and close header dropdown by click outside
var $document = jQuery(document),
$window = jQuery(window),
$header = jQuery('header.header-hc2'),
$container = $header.children('.container'),
$secondNav = $header.children('.secondary-navigation'),
$secondContainer = $secondNav.children('.container'),
onMobile = false,
scrollTop = 0,
scrollTimeout = false,
headerStatus = false;
function HC2toggleHeader() {
if ($document.scrollTop() >= 400) {
$container.slideUp('fast');
$secondNav.addClass('second-nav-slideUp');
} else {
$container.slideDown('fast');
$secondNav.removeClass('second-nav-slideUp');
}
}
function HC2toggleHeader2() {
// if the timer has done
if(scrollTimeout) return false
scrollTimeout = setTimeout(function(){
var newScrollTop = $document.scrollTop();
var range = newScrollTop - scrollTop;
scrollTop = newScrollTop;
if(range >= 100 && headerStatus != 'slideUp') {
$container.slideUp('fast');
$secondNav.addClass('second-nav-slideUp');
headerStatus = 'slideUp';
}
else if(range <= -100 && headerStatus != 'slideDown') {
$container.slideDown('fast');
$secondNav.removeClass('second-nav-slideUp');
headerStatus = 'slideDown';
}
scrollTimeout = false;
}, 250);
}
function HC2setMobile() {
var width = $window.width();
if(width <= 768) {
$header.addClass('hc2-header-mobile');
onMobile = true;
}
else {
$header.removeClass('hc2-header-mobile');
$secondContainer.children('ul.menu').css('display','');
onMobile = false;
}
}
$document.scroll(function() {
HC2toggleHeader2();
});
$window.resize(function() {
HC2setMobile();
});
$document.ready(function($){
HC2toggleHeader();
HC2setMobile();
$secondContainer.children('.navigation-title').toggle(function(){
if(onMobile) {
$secondContainer.children('ul.menu').slideDown();
$(this).addClass('hc2-menu-open');
}
}, function() {
if(onMobile) {
$secondContainer.children('ul.menu').slideUp();
$(this).removeClass('hc2-menu-open');
}
});
})
$window.click(function() {
//Hide the menus if visible
if(onMobile && $secondContainer.children('.navigation-title').hasClass('hc2-menu-open')) {
$secondContainer.children('.navigation-title').trigger('click');
}
});
$secondContainer.children('ul.menu').click(function(event){
event.stopPropagation();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment