Skip to content

Instantly share code, notes, and snippets.

@ryenski
Last active August 5, 2017 20:43
Show Gist options
  • Save ryenski/bab956e96fe86083fe2bb2f3cb1fd186 to your computer and use it in GitHub Desktop.
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/)
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