Skip to content

Instantly share code, notes, and snippets.

@luislobo14rap
Last active May 2, 2018 20:45
Show Gist options
  • Save luislobo14rap/4e72ab9fd6fa3fa4ffaa2922c5a6fb3e to your computer and use it in GitHub Desktop.
Save luislobo14rap/4e72ab9fd6fa3fa4ffaa2922c5a6fb3e to your computer and use it in GitHub Desktop.
$(function(){
//console.info('menu menuHighlight running');
let menuElement = $('.mc-menu')
, allElements = $('.mc-menu__top__logo, .mc-menu__top__menu-button')
, anchorMap = [];
$('.mc-menu__top__logo, .mc-menu__top__menu-button').each(function(){
anchorMap.push( $( $(this).attr('href') ) );
});
//first run
menuHighlight(menuElement, anchorMap, allElements);
setTimeout(function(){
menuHighlight(menuElement, anchorMap, allElements);
}, 250);
//events to run
$(window).on('scroll', function(){
//console.info('scroll');
menuHighlight(menuElement, anchorMap, allElements);
setTimeout(function(){
menuHighlight(menuElement, anchorMap, allElements);
}, 250);
});
$(window).on('resize', function(){
//console.info('resize');
menuHighlight(menuElement, anchorMap, allElements);
setTimeout(function(){
menuHighlight(menuElement, anchorMap, allElements);
}, 250);
});
function menuHighlight(menuElement, anchorMap, allElements){
let scrollYNow = scrollY
, getPositions = []
, menuHeight = menuElement.innerHeight()
, windowHeight = $(window).innerHeight / 4
, active = false;
anchorMap.forEach(function(item, i){
getPositions.push({
'min': item.offset().top,
'max': typeof anchorMap[i+1] != 'undefined' ? ( anchorMap[i+1].offset().top - 1 ) : 999999
});
});
//fix getPositions
getPositions.pop();
getPositions[ getPositions.length - 1 ].max = 999999;
getPositions.forEach(function(item, i){
//console.info('scrollYNow: ' + scrollYNow, 'item.min: ' + item.min, 'item.max: ' + item.max, 'i: ' + i );
if( scrollYNow >= item.min - menuHeight - 40 && scrollYNow <= item.max - menuHeight - 40 && !active ){
allElements.removeClass('active');
allElements.eq(i).addClass('active');
setTimeout(function(){
allElements.eq(i).addClass('active');
});
active = true;
};
});
if( active == false ){
allElements.removeClass('active');
anchorMap[ anchorMap.length - 1 ].addClass('active');
anchorMap[ anchorMap.length - 1 ].addClass('active');
};
return false;
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment