UNPKG

scrolled-header

Version:

Add active class to fixed header while scrolling down and remove when scrolling up.

57 lines (56 loc) 2.04 kB
"use strict"; exports.__esModule = true; var Header = /** @class */ (function () { function Header(_a) { var target = _a.target, _b = _a.offset, offset = _b === void 0 ? 50 : _b, _c = _a.className, className = _c === void 0 ? "scrolled" : _c, _d = _a.backScroll, backScroll = _d === void 0 ? true : _d; var _this = this; this.target = null; this.scroller = 0; this.toggler = false; this.backScroll = true; this.toggleHandler = function () { _this.toggle(); }; if (!target) throw new Error("The Header Element is required"); this.target = target; this.offset = offset; this.className = className; this.scroller = 0; this.toggler = false; this.backScroll = backScroll; if (this.target) { this.toggle(); window.addEventListener("scroll", this.toggleHandler); } return this; } Header.prototype.toggle = function () { var scroll = document.documentElement.scrollTop; if (this.scroller - scroll < this.offset && scroll - this.scroller < this.offset) return false; var oldScroller = this.scroller; this.scroller = scroll; if (oldScroller > this.scroller && this.backScroll) { if (this.toggler) { this.target.classList.remove(this.className); this.toggler = false; } } else { if (this.scroller > this.offset && !this.toggler) { this.target.classList.add(this.className); this.toggler = true; } else if (this.scroller <= this.offset && this.toggler) { this.target.classList.remove(this.className); this.toggler = false; } } }; Header.prototype.stop = function () { window.removeEventListener("scroll", this.toggleHandler); }; return Header; }()); exports["default"] = Header;