Created
January 15, 2020 20:39
-
-
Save jesperlandberg/f469ddd96a970e81db6f1a2d432a7d64 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import gsap from 'gsap' | |
| class SimpleDraggable { | |
| constructor() { | |
| this.bindAll() | |
| this.el = document.querySelector('.js-slider-wrap') | |
| this.inner = this.el.querySelector('.js-slider-inner') | |
| this.slides = this.el.querySelectorAll('.js-slide') | |
| this.snapPoints = [] | |
| this.target = 0 | |
| this.current = 0 | |
| this.ease = 0.1 | |
| this.on = 0 | |
| this.max = 0 | |
| this.speed = 2 | |
| this.dragging = false | |
| this.init() | |
| } | |
| bindAll() { | |
| ['animate', 'onDown', 'onUp', 'onMove'] | |
| .forEach(fn => this[fn] = this[fn].bind(this)) | |
| } | |
| init() { | |
| this.getSnapPoints() | |
| this.getBounding() | |
| this.animate() | |
| } | |
| addEvents() { | |
| this.el.addEventListener('mousedown', this.onDown) | |
| window.addEventListener('mouseup', this.onUp) | |
| window.addEventListener('mousemove', this.onMove) | |
| } | |
| getSnapPoints() { | |
| this.slides.forEach(slide => { | |
| this.snapPoints.push(slide.getBoundingClientRect().top) | |
| }) | |
| } | |
| getBounding() { | |
| const { height } = this.inner.getBoundingClientRect() | |
| this.max = height - window.innerHeight | |
| } | |
| animate() { | |
| this.current += (this.target - this.current) * this.ease | |
| this.inner.style.transform = `translate3d(0, ${this.current}px, 0)` | |
| requestAnimationFrame(this.animate) | |
| } | |
| onDown({ clientY }) { | |
| this.dragging = true | |
| this.on = this.target - (clientY * this.speed) | |
| } | |
| onMove({ clientY }) { | |
| if (!this.dragging) return | |
| this.target = this.on + (clientY * this.speed) | |
| this.target = gsap.utils.clamp(0, this.max, this.target) | |
| } | |
| onUp() { | |
| if (!this.dragging) return | |
| this.dragging = false | |
| this.target = gsap.utils.snap(this.snapPoints, this.target) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment