baptistebriel / smooth-scrolling

smooth scrolling and parallax effects on scroll
MIT License
612 stars 75 forks source link

StickySidebar with Smooth-Scroll #95

Closed wezzou1 closed 5 years ago

wezzou1 commented 6 years ago

Hi, I'm trying to build an StickySidebar, I realised that it's not possible to set position:fixed with smooth-scroll, so I have to transform-count the scroll position,

I want something like this. https://github.com/WeCodePixels/theia-sticky-sidebar

Can someone help me out with a stickysidebar that's work smooth together with smooth-scrolling.

My code right now..

class StickySidebar {
    constructor( opts = {} ) {
        this.bind()

        this.dom = {
            el: document.querySelector('[data-sticky]'),
            content: document.querySelector('.o-content'),
            sidebarInner: document.querySelector('.o-sidebar__inner')
        }

        this.bounding = this.dom.content.getBoundingClientRect()

        this.sticky = false

        this.init()
    }

    bind() {
        ['run']
        .forEach((fn) => this[fn] = this[fn].bind(this))
    }

    run() {
        const current = window.scrollY
        const transform = current - (this.bounding.top - 200)
        const bottom = this.bounding.bottom - (this.dom.sidebarInner.offsetHeight + 300)
        const top = this.bounding.top - 200

        if ( current > top && current < bottom ) {
            this.dom.el.style.transform = `translate3d(0, ${transform}px, 0.1px)`
            this.dom.el.classList.add('is-sticky')
            this.sticky = true
        } else {
            this.dom.el.classList.remove('is-sticky')
            this.sticky = false
        }

    }

    addEvents() {
        TweenMax.ticker.addEventListener('tick', this.run, this)
    }

    init() {
        this.addEvents()
    }
}