I was wondering how sites like Facebook, with their timeline feature, float a certain element (usually a menu bar, or sometimes a social plugin, etc) when the user has scrolled past a point such that the top of the element is off the screen, etc.
This could be seen as a more general JavaScript (jQuery?) event firing when the user has scrolled to a certain element, or scrolled down a certain number of pixels.
Obviously it would require toggling the CSS property from:
#foo { position: relative; }
to
#foo { position: fixed; }
Or with jQuery, something like:
$('#foo').css('position', 'fixed');
Another way I have seen this implemented is with blogs, where a popup will be called when you reach the bottom, or near the bottom of a page. My question is, what is firing that code, and could you link or provide some syntax/ semantics/ examples?
Edit: I’m seeing some great JS variants coming up, but as I am using jQuery, I think the plugin mentioned will do just nicely.
Take a look at this jsfiddle: http://jsfiddle.net/remibreton/RWJhM/2/
In this example, I’m using
document.onscroll = function(){ //Scroll event }to detect a scroll event on the document.I’m then calculating the percentage of the page scrolled based on it’s height.
(document.body.scrollTop * 100 / (document.body.clientHeight - document.documentElement.clientHeight)).document.body.scrollTopbeing the number of pixels scrolled from the top,document.body.clientHeightbeing the height of the entire document anddocument.documentElement.clientHeightbeing the visible portion of the document, a.k.a. the viewport.Then you can compare this value to a target percentage, an execute
JavaScript.if(currentPercentage > targetPercentage)…Here’s the whole thing:
If you prefer jQuery, here is the same example translated into everybody’s favorite library: http://jsfiddle.net/remibreton/8NVS6/1/