-
-
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
This file contains 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 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