Scroll Element with Window once a user scrolls past the element


/ Published in: jQuery
Save to your folder(s)

I wrote this from scratch :)

Basically I wanted a DIV to scroll with the window but it's not visible to begin with on the page. So this does it when the user scrolls past the beginning of that element.


Copy this code and paste it in your HTML
  1. // Scroll Element with Window
  2. // When window scrolls do this
  3. $(window).scroll(function() {
  4.  
  5. // scrollYpos variable is amount of pixels scrolled from the top of the page
  6. var scrollYpos = $(document).scrollTop();
  7.  
  8. // If Pixels from top is greater than 550 (That was the number of pixels between the top of page and my scrolling element. you may want to be more fancy)
  9. if (scrollYpos > 550 ) {
  10.  
  11. // Animate margin top of scrolling element -540px (remember my 550 above? this is -10px for a nice margin)
  12. $('#scrollingDiv').animate({'margin-top': scrollYpos - 540 }, {duration: 200, queue: false});
  13.  
  14. } else {
  15.  
  16. // If you scrolled up to quickly then it would leave the div where it was. This pushes it back to it's starting position
  17. $('#scrollingDiv').animate({'margin-top': 0 }, {duration: 200, queue: false});
  18. }
  19. }); // Scroll Element with Window

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.