Last active
August 5, 2017 20:43
-
-
Save ryenski/bab956e96fe86083fe2bb2f3cb1fd186 to your computer and use it in GitHub Desktop.
Pure-css version of the parallax effect from Bourbon Refills (http://refills.bourbon.io/components/)
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
document.addEventListener('turbolinks:load', function(){ | |
var el = document.getElementById('js-parallax-window') | |
if (el) { | |
parallax(el); | |
} | |
window.addEventListener('scroll', function(e){ | |
if (el) { | |
parallax(el); | |
} | |
}) | |
}); | |
function parallax(el){ | |
var plxBackground = el.querySelector('#js-parallax-background') | |
var plxWindow = el | |
var plxWindowTopToPageTop = offset(plxWindow).top; | |
var windowTopToPageTop = document.body.scrollTop; | |
var plxWindowTopToWindowTop = plxWindowTopToPageTop - windowTopToPageTop; | |
var plxBackgroundTopToPageTop = offset(plxBackground).top; | |
var windowInnerHeight = document.body.offsetHeight; | |
var plxBackgroundTopToWindowTop = plxBackgroundTopToPageTop - windowTopToPageTop; | |
var plxBackgroundTopToWindowBottom = windowInnerHeight - plxBackgroundTopToWindowTop; | |
var plxSpeed = 0.5; | |
plxBackground.style.top = - (plxWindowTopToWindowTop * plxSpeed) + 'px'; | |
} | |
function offset(el){ | |
var rect = el.getBoundingClientRect(); | |
return { | |
top: rect.top + document.body.scrollTop, | |
left: rect.left + document.body.scrollLeft | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment