Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript or Jquery: Scroll to Fixed position div

I want a html div which will scroll when user scroll down the page and it will get to fixed position when it's parent tag ends. For example:- See this link http://www.9gag.com/ they have alot to posts on one page. When we scroll one post and go to end of the first post, the title and share buttons become to fixed position and then the second post do the same and same for the next posts. Just exactly like that. How can we do this in Jquery or raw javascript or in css.

like image 403
John Preston Avatar asked Oct 08 '22 08:10

John Preston


2 Answers

Maybe you want to try this plugin: http://labs.anthonygarand.com/sticky/ Sticky is a jQuery plugin that gives you the ability to make any element on your page always stay visible by making the element to be floated when they has reached the limit.

like image 166
Taufik Nurrohman Avatar answered Oct 13 '22 11:10

Taufik Nurrohman


$(window).scrollTop() will give you the number of pixels scrolled down in the browser, $('postcontainer').offset() will give you the x,y positions of a post container.

So if you bind an event to $(window).scroll() or to the mousescroll, you can check if the postcontainer's offset().top is less than the window.scrollTop. If it is then you start moving the item down relative to the post container. When doing this you need to keep track of the post container's height and the moving element's height to make sure it doesn't go down past the bottom of the container.

So if postcontainer.height - movingelement.position().top >= movingelement.height() then you need to fix the position of the moving element. Do the opposite while scrolling back up.

Hopefully this will get you thinking and starting to kick out some code.

like image 24
Rob Avatar answered Oct 13 '22 11:10

Rob