Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- {% javascript %}
- class StickyHeader extends HTMLElement {
- constructor() {
- super();
- }
- connectedCallback() {
- this.header = document.getElementById('shopify-section-header');
- this.headerBounds = {};
- this.currentScrollTop = 0;
- this.preventReveal = false;
- this.onScrollHandler = this.onScroll.bind(this);
- this.hideHeaderOnScrollUp = () => this.preventReveal = true;
- this.addEventListener('preventHeaderReveal', this.hideHeaderOnScrollUp);
- window.addEventListener('scroll', this.onScrollHandler, false);
- this.createObserver();
- }
- disconnectedCallback() {
- this.removeEventListener('preventHeaderReveal', this.hideHeaderOnScrollUp);
- window.removeEventListener('scroll', this.onScrollHandler);
- }
- createObserver() {
- let observer = new IntersectionObserver((entries, observer) => {
- this.headerBounds = entries[0].intersectionRect;
- observer.disconnect();
- });
- observer.observe(this.header);
- }
- onScroll() {
- const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
- if (scrollTop > this.currentScrollTop && scrollTop > this.headerBounds.bottom) {
- requestAnimationFrame(this.hide.bind(this));
- } else if (scrollTop < this.currentScrollTop && scrollTop > this.headerBounds.bottom) {
- if (!this.preventReveal) {
- requestAnimationFrame(this.reveal.bind(this));
- } else {
- window.clearTimeout(this.isScrolling);
- this.isScrolling = setTimeout(() => {
- this.preventReveal = false;
- }, 66);
- requestAnimationFrame(this.hide.bind(this));
- }
- } else if (scrollTop <= this.headerBounds.top) {
- requestAnimationFrame(this.reset.bind(this));
- }
- this.currentScrollTop = scrollTop;
- }
- hide() {
- this.header.classList.add('shopify-section-header-hidden', 'shopify-section-header-sticky');
- }
- reveal() {
- this.header.classList.add('shopify-section-header-sticky', 'animate');
- this.header.classList.remove('shopify-section-header-hidden');
- }
- reset() {
- this.header.classList.remove('shopify-section-header-hidden', 'shopify-section-header-sticky', 'animate');
- }
- }
- customElements.define('sticky-header', StickyHeader);
- {% endjavascript %}
- <style>
- #shopify-section-header {
- z-index: 3;
- }
- .shopify-section-header-sticky {
- position: sticky;
- top: 0;
- background: #fff;
- }
- .shopify-section-header-hidden {
- transform: translateY(-100%);
- }
- #shopify-section-header.animate {
- transition: transform 0.15s ease-out;
- }
- </style>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement