I want to postion a DIV
inside a page such that it is visible to the user even if the user vertically scrolls the page.
The page has a heading at the top of the page which is 75 px
tall. Now when the user is at the top of the page and has not scrolled vertically, the DIV
must be postioned below the heading. However, once the user scrolls the page causing the heading to go out of sight, the same DIV
must now be position at the top of the page (i.e. near the top edge of the browser viewport)
My big concern is the support for window.onscroll
event on browsers. I checked QuirksMode for compatibility (http://www.quirksmode.org/dom/events/scroll.html). It seems to have decent compatibility on IE and Firefox. However the Safari and Chrome support seems a bit quirky. And both these browsers are part of my target browsers' list.
Can anybody tell me if the window.onscroll
event is an effective way of detecting page/frame scrolls? Any other suggestions?
P.S. I have considered using the CSS position: fixed
rule. It is close to the solution but the DIV
is just stuck to one position and I cannot have it adaptively move based on the visiblity of the heading.
Thanks!
Here's another alternative method you could try. I use it to position a toolbar div on top of the page (works for ipad too).
Instead of using the onScroll event, I am using a timer to fire every 500ms to detect where the windows is scrolled to via scrollTop
. You could adjust the timer to about 200ms if you like.
Here's a stripped down sample of my code:
This jquery code checks when and if my dom element div named "floatlayer" (which is a div that contains my buttons toolbar) is ready and then calls the function setRepeater
$(#floatlayer").ready(function () {
return setRepeater();
});
Then, this is the function that creates a timer to keep executing the function "keepIncrease" every 500ms
function setRepeater() {
aTimer = window.setInterval("keepIncrease()", 500);
return false;
}
This is the function keepIncrease() which is repeated every 500ms and is responsible to position the toolbar div based on the current window scrolled position :
function keepIncrease() {
var divToolbar = $("#floatlayer")[0];
var currentPos = $(window).scrollTop();
divToolbar.style.top = currentPos + "px";
return false;
}
Something else out of topic: If your content is inside an iframe, you could also use $(window.parent).scrollTop() instead of $(window).scrollTop()