4

I am trying to do a presentation website and wanted to make an element as if it was floating in air. I have managed to get the thing working (for header section) but by the time you reach the element it is already too outset off of its original position. Currently my javascript is calculating the distance between the element and top of the page.

$(document).ready(function() {
 
 $(window).scroll(function () { 
  
   $('.parallax-element-container').css({
    
     'bottom' : -($(this).scrollTop()/8)+"px"
     
      }); 
 
   });
   
 });

I have uploaded the issue to codepen to give you an idea, any suggestions are welcome.

http://codepen.io/marolt/details/PqNPYj/

peterh
  • 11,875
  • 18
  • 85
  • 108
Žan Marolt
  • 136
  • 1
  • 3
  • 10

1 Answers1

1

You can wait until the window scrollTop is closer to your target, then start moving it.

Example: http://codepen.io/anon/pen/aONWEP

$(document).ready(function() {
  var parallaxTop = $('.parallax-element-container').offset().top;
  var parallaxStart = parallaxTop * .9;

  $(window).scroll(function() {
    if ($(this).scrollTop() >= parallaxStart) {
      $('.parallax-element-container').css({
        'bottom': -(($(this).scrollTop() - parallaxStart) / 2) + "px"
      });
    }
  });

});
Bitwise Creative
  • 4,035
  • 5
  • 27
  • 35
  • This works great, however instead of fixed 2700, how would I go about getting the position of the element and maybe decreasing it by 20%? Should I create a function for this? – Žan Marolt May 13 '15 at 09:12
  • Naa, you don't need a function. You can just set some variables on DOM load. I've updated my answer. – Bitwise Creative May 13 '15 at 16:42
  • Thank you so much, I have been struggling with this! One more question though, instead of calling it by class; just in case I would want for example two .parallax-element-containers on one page, how would i tackle that. again thanks for the help :) – Žan Marolt May 14 '15 at 07:22
  • No problem, thank you for accepting my answer. For multiple parallax sections, you'd just need more setup, an array, a loop, etc. Example: http://codepen.io/anon/pen/pJyZMM – Bitwise Creative May 14 '15 at 16:10
  • No, thank you for helping me. I did a loop aswell but your code is much cleaner.. – Žan Marolt May 15 '15 at 06:13