I'm having a hard time giving a good description of this, but bear with me:
If I have a page structed like this
<h2>Chapter 1</h2>
<p>Lots of text that has mutiple screen worths of content</p>
<h2>Chapter 2</h2>
<p>Lots of text...</p>
I'd like to have "Chapter 1" absolutely positioned or whatever at the top of the page until the user scrolls down to where "Chapter 2" starts, at which point now "Chapter 2" is displayed at the top of the page.
We can add wrapper classes and divs if needed. Solutions that use JQuery would be great.
The vertical position of the element to be stuck can also be modified with the help of the 'top' property. It can be given a value of '0px' to make the element leave no space from the top of the viewport, or increased further to leave space from the top of the viewport.
To make an element sticky, do: make_sticky('#sticky-elem-id'); When the element becomes sticky, the code manages the position of the remaining content to keep it from jumping into the gap left by the sticky element. It also returns the sticky element to its original non-sticky position when scrolling back above it.
Add a z-index on header; 1 should be sufficient.
Using jQuery, see this question: What is the simplest jQuery way to have a 'position:fixed' (always at top) div? As a note, top: 0; sets the distance from the top of the window to the top of the div to 0 (since px or em isn't noted, the browser doesn't care). It's obvious, but good to know how exactly it works.
Rather than changing the positioning of your Headings, you can create a div that is always at the top of the screen and clone your headings into it as you detect that the user has scrolled past. See a working demo: http://jsfiddle.net/8sANt/
JS:
$(document).scroll(function () {
var sticky = $('#sticky'), h2 = $('h2:first');
if (!sticky.length)
sticky = $('<div id="sticky">').appendTo('body');
$('h2').each(function () {
if ($(this).parents('#sticky').length) return; // Ignore cloned headings
if ($(this).offset().top > $(window).scrollTop())
return false; // Exit loop
h2 = $(this);
});
sticky.empty().append(h2.clone());
});
CSS:
#sticky {
position: fixed;
top: 0;
left: 0;
width: 100%;
background: white;
}
If I understand correctly you want something similar to Google's Image paging right? Where it displays the current page you're on at the top until the next page scrolls past and then becomes the new page.
What you want to do is when the user is scrolling, check to see the position of the H2 elements, if it is less than the scrolltop of it's parent container, make its text the candidate for being the one that is in the absolutely positioned element at the top. Once you hit a H2 that isn't in the negative break out of the loop and add the text to the absolutely positioned element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With