Search code examples
jqueryanimationscrolljquery-waypoints

How do I animate on scroll inside a waypoint function?


I have images that appear from the left and right of the screen as the user scrolls down.

Using divPosition = $('div').offset().top; to get the position of the containing element I subtract the value from scrollValue = $(document).scrollTop(); and apply the value to position left on an absolutely positioned image.

The offset of the containing div is calculated on refresh and resize. Without resizing the window the x=scrollValue - divPosition varies on refresh depending how far the page is scrolled. I want it to be consistent. Is there a better way of getting this type of animation to work.

For example is it possible to trigger the animation using the vertical scroll as the x value with waypoints?

    window.onresize=function(){
        divPosition = $('div').offset().top;
    };

    $(document).scroll(function(){
        scrollValue = $(document).scrollTop();
        x = scrollValue - divPosition;
    }

Here is a link to the site. As an when I discover the cause of the problems I will post the relevant section of code in this question.

http://www.otherdewi.com/gg.html


Solution

  • Finally solved the issues.

    1. Cleaned up my code adding clearfix to ensure the height of each section was reporting correctly.
    2. Wrapped the funcitons animated on scroll inside Waypoint

      $('#about').waypoint(function(direction){
          $(document).scroll(function(){...});
      });
      
    3. I added a window.onresize function to recalculate the position on the relevant container to account for the reflow of content.

      window.onresize = function(){
          tourPosition=$tours.offset().top;
          winH = window.innerHeight;
      };
      
    4. To get a value to animate an elements from the left and right on scroll. I calculated scrollposition of the document + window height - position of the containing element.

      scrollPos = $(this).scrollTop();
      var posX = scrollPos - tourPosition + winH;
      
    5. An offset was then added posX.

      $('pic1').css({'left':posX-600});
      

      $('pic2').css({'right':posX-800}); $('pic3').css({'left':posX-1200});