Last active
June 26, 2016 20:16
-
-
Save YoussefKababe/dd6f37b7b019ff72955828cf4b0bcb3c 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