Advertisement
Guest User

Untitled

a guest
Mar 25th, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. let $back;
  2. const BACKGROUND_ID = '#background', SCROLL_SELECTOR = 'main';
  3. //hard-coded backgoround image size to start parallax asap
  4. let sizes = {
  5. width: 1678, height: 2481
  6. };
  7.  
  8. $(document).on('turbolinks:load', () => {
  9. $(scrollSelector).on('scroll', handleParallax);
  10. setSize();
  11. setBackPosition('translateY(0px)', true)
  12. })
  13. function setSize(){
  14. $back = $(BACKGROUND_ID);
  15. const imgSrc = $back.find('img').attr('src');
  16. const backImg = new Image();
  17. backImg.onload = (e) => {
  18. sizes = {
  19. width: $back.width(),
  20. height: $back.height(),
  21. }
  22. handleParallax(e, true);
  23. }
  24. backImg.src = imgSrc;
  25. }
  26. $(window).resize(setSize);
  27. $(document).on('turbolinks:before-visit', () => setBackPosition('translateY(0px)', true));
  28. $(window).on('scroll', handleParallax);
  29.  
  30. function handleParallax(e, animate = false){
  31. const $this = $(e.currentTarget);
  32. let height;
  33. if($this.is(SCROLL_SELECTOR)){
  34. const heights = $this.children().map((i,elem) => $(elem).outerHeight(true));
  35. height = Math.max(...heights);
  36. }
  37. else{
  38. height = $(scrollSelector).outerHeight(true);
  39. }
  40. // don't exagerate it...
  41. height = Math.max(height, 3*window.innerHeight);
  42.  
  43. let percentageScrolled = ($this.scrollTop() / (height - window.innerHeight));
  44. percentageScrolled = Math.min(Math.max(0, percentageScrolled), 100);
  45.  
  46. let transform = Math.ceil(percentageScrolled*(sizes.height - window.innerHeight));
  47. transform = `translateY(-${transform}px)`;
  48.  
  49. window.requestAnimationFrame(() => setBackPosition(transform, animate));
  50. }
  51.  
  52. function setBackPosition(transform, animate = false){
  53. const fn = animate ? 'transition' : 'css';
  54. $back[fn]({ transform })
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement