• # November 20, 2008 at 11:35 am

    Most people here are probably familiar with QuirksMode. Go to the site and note the "show site navigation" link at the top left (it’s not on the front page, but any of the inner pages, like About). Scroll the page down and watch what happens – the link scrolls with the page until it’s about to scroll out of view, at which point it stays fixed in position!

    Does anyone have any idea how this works? I can’t figure it out. It’s not just straight fixed position, because the link will scroll with the page initially. When inspecting it with Firebug, I can see the value of "top" changes dynamically as you scroll – he must have some JavaScript that does this.

    Any insight into this would be much appreciated!

    # November 20, 2008 at 11:55 am

    This reply has been reported for inappropriate content.

    Hmm…upon further inspection it looks like this is the function:

    function setMenuOffset() {
    var header = document.getElementById(‘header’);
    if (!header) return;
    var currentOffset = document.documentElement.scrollTop || document.body.scrollTop; // body for Safari
    var startPos = parseInt(setMenuOffset.initialPos) || 190;
    var desiredOffset = startPos – currentOffset;
    if (desiredOffset < 10)
    desiredOffset = 10;
    if (desiredOffset != parseInt( = desiredOffset + 'px';

    var currentLeftOffset = document.documentElement.scrollLeft || document.body.scrollLeft; // body for Safari
    if (currentLeftOffset != – parseInt( = '-' + currentLeftOffset + 'px';

    It looks like var currentOffset is the distance that you’ve scrolled down the page (so this is initially 0). startPos is the initial position of the menu (190px from the top). So he takes 190, subtracts the distance you’ve scrolled, and uses that as the new value for top – that causes the menu to move with the page.

    The secret is this: if 190 minus the scroll distance is less than 10, he keeps the value for top set at 10. So as soon as you scroll down 181px or more, the menu stays fixed 10px from the top.

    Very, very clever. And something I would never be able to come up with on my own, as I don’t have the JavaScript knowledge to write something like this :lol:

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.