Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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 })
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement