I'm trying to implement a "scroll-then-fixed" HTML/CSS layout. The idea is that the user can scroll the page a little - until the site header is out of view - at which point the main product image on the page would be fixed to the top of the page, and the rest of the page contents would continue to scroll. Here's a mockup of what I'm trying to achieve:
As you can see, at first, the site header is visible, but the user can scroll down. When the product image (in yellow) reaches the top of the page, it becomes fixed to the top of the window.
The way I'm doing this now is to listen to the scroll event from the document (using jQuery), and then change the product image's CSS position property when the user has scrolled past the height of the header. I've tried both CSS position fixed and absolute, but each has their problems:
- If I switch to fixed positioning, on mobile devices (both iOS and Android) the scrolling is very smooth, and the product image is locked to the top of the window perfectly. However contents of the product image disappear if you keep your finger on the screen and the div switches from position relative to position fixed. They will redraw as soon as you release, but it looks broken while you're scrolling. This only happens on mobile devices or an emulator; not in a desktop browser. JSBin Example.
- If I switch to absolute positioning (and provide a top offset), I don't have the problem that the phone stops drawing the product image, however, the scrolling is really jagged. The product image jumps as you scroll. JSBin Example.
For #1, I do something like this:
var docScrollTop = $(window).scrollTop();
if (docScrollTop >= $('.dev-header-fixed').height()) {
$fixableTop.css({
'position': 'fixed',
'top': 0,
'z-index': 99,
'display': 'block'
});
}
... and for #2, I do this:
var docScrollTop = $(window).scrollTop();
if (docScrollTop >= $('.dev-header-fixed').height()) {
$fixableTop.css({
'position': 'absolute',
'top': docScrollTop,
'z-index': 99,
'display': 'block'
});
}
I've provided full, working JSBin example links to both approaches above. Is there some way to prevent mobile devices from hiding the contents when the switch to fixed position happens?