Skip to content

Instantly share code, notes, and snippets.

@maysam
Forked from YoussefKababe/parallax-mixin.js
Created June 26, 2016 20:16
Show Gist options
  • Save maysam/3813d64688c1951f630d9e2c2fe82397 to your computer and use it in GitHub Desktop.
Save maysam/3813d64688c1951f630d9e2c2fe82397 to your computer and use it in GitHub Desktop.
A RiotJS mixin that adds parallax effect to any tag with a background-image property
import kefir from 'kefir'
const parallaxMixin = {
init: function() {
let ratio = this.opts.parallaxRatio || 1
this.on('mount', () => {
this.updateBGPosition(ratio)
let scrolls = kefir.fromEvents(window, 'scroll')
let unmounts = kefir.fromEvents(this, 'unmount')
scrolls.throttle(10, { leading: false }).takeUntilBy(unmounts).onValue(() => {
window.requestAnimationFrame(() => this.updateBGPosition(ratio))
})
})
},
updateBGPosition: function(ratio) {
let element = this.root
let elementPosition = element.getBoundingClientRect()
let distanceFromMiddle = 100 - ((elementPosition.top + element.offsetHeight / 2) * 100) / (window.innerHeight / 2)
let newBGPosition = 50 + distanceFromMiddle * ratio
element.style.backgroundPosition = `center ${newBGPosition}%`
}
}
export default parallaxMixin
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment