active-scroll-navigation
Version:
Navigation will change active state when user scroll.
1 lines • 1.66 kB
JavaScript
;Object.defineProperty(exports,"__esModule",{value:!0});var _createClass=function(){function r(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(e,t,n){return t&&r(e.prototype,t),n&&r(e,n),e}}();function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var ACTIVE_SCROLL=function(){function t(e){var r=this;_classCallCheck(this,t),this.activeItem=0,this.setPros=function(){r.pros=[],r.navArray.forEach(function(e){var t=e.getAttribute("href"),n=document.querySelector(t);r.pros.push(n.offsetTop-r.offSet)})},this.scrollLocation=function(e){for(var t=0;t<r.pros.length;t++)if(t<r.pros.length-1){var n=r.pros[t+1];if(e>=r.pros[t]&&e<n)return t}else if(t===r.pros.length-1&&e>=r.pros[t])return t},this.checkNav=function(e){var t=r.scrollLocation(window.pageYOffset);if(r.activeItem!==t){var n=r.activeItem;r.activeItem=t,r.navItems[n].classList.remove(r.activeString),r.navItems[t].classList.add(r.activeString)}},this.nav=document.querySelector(e.nav),this.offSet=e.offSet||0,this.navItems=this.nav.children,this.navArray=Array.from(this.navItems),this.activeString=e.activeClass||"main-nav__item--active",this.setPros(),this.eventsSroll(),this.events()}return _createClass(t,[{key:"eventsSroll",value:function(){window.addEventListener("scroll",this.checkNav,!1)}},{key:"events",value:function(){window.addEventListener("resize",this.setPros,!1)}},{key:"eventsSrollOff",value:function(){window.removeEventListener("scroll",this.checkNav,!1)}}]),t}();exports.default=ACTIVE_SCROLL;