Skip to content

Instantly share code, notes, and snippets.

@walidvb
Created March 25, 2017 13:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save walidvb/17d1b1e3839168dc92d06e2bf3300807 to your computer and use it in GitHub Desktop.
Save walidvb/17d1b1e3839168dc92d06e2bf3300807 to your computer and use it in GitHub Desktop.
Mapping 2017 parallax code
let $back;
const BACKGROUND_ID = '#background', SCROLL_SELECTOR = 'main';
//hard-coded backgoround image size to start parallax asap
let sizes = {
width: 1678, height: 2481
};
$(document).on('turbolinks:load', () => {
$(scrollSelector).on('scroll', handleParallax);
setSize();
setBackPosition('translateY(0px)', true)
})
function setSize(){
$back = $(BACKGROUND_ID);
const imgSrc = $back.find('img').attr('src');
const backImg = new Image();
backImg.onload = (e) => {
sizes = {
width: $back.width(),
height: $back.height(),
}
handleParallax(e, true);
}
backImg.src = imgSrc;
}
$(window).resize(setSize);
$(document).on('turbolinks:before-visit', () => setBackPosition('translateY(0px)', true));
$(window).on('scroll', handleParallax);
function handleParallax(e, animate = false){
const $this = $(e.currentTarget);
let height;
if($this.is(SCROLL_SELECTOR)){
const heights = $this.children().map((i,elem) => $(elem).outerHeight(true));
height = Math.max(...heights);
}
else{
height = $(scrollSelector).outerHeight(true);
}
// don't exagerate it...
height = Math.max(height, 3*window.innerHeight);
let percentageScrolled = ($this.scrollTop() / (height - window.innerHeight));
percentageScrolled = Math.min(Math.max(0, percentageScrolled), 100);
let transform = Math.ceil(percentageScrolled*(sizes.height - window.innerHeight));
transform = `translateY(-${transform}px)`;
window.requestAnimationFrame(() => setBackPosition(transform, animate));
}
function setBackPosition(transform, animate = false){
const fn = animate ? 'transition' : 'css';
$back[fn]({ transform })
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment