Is there a way to set the window's scroll position without using scroll() or scrollTo()?

3.7k views Asked by At

...the reason I ask is that Safari has a bug in its implementation of scroll() that is breaking my UI.

Imagine a page:

<body>
    <div id="huge" style="width: 4000px; height: 4000px;"></div>
</body>

...so that you get both horizontal and vertical scrollbars. Now, normally when you press the scrollbar, the page scrolls (vertically). For the purposes of our fancy UI we don't want that to happen, so we squash the keyDown event:

window.onkeydown = function(e) {
    if(e.keyCode == 32)
    {
        return false;
    }
};

This works great...unless we decide that instead of preventing scrolling altogether, we want our own, custom scrolling behavior:

window.onkeydown = function(e) {
    if(e.keyCode == 32)
    {
        window.scroll(foo, bar); // Causes odd behavior in Safari
        return false;
    }
};

In other browsers (Chrome, Firefox), this will instantaneously move the window's scroll position to the desired coordinates. But in Safari this causes the window to animate to the desired scroll position, similar to the scrolling animation that takes place if you press the space bar.

Note that if you trigger this scroll off of any key OTHER than the space bar, the animation does not take place; the window scrolls instantly as in other browsers.

If you happen to be scrolling, say, 1000 pixels or more, then the animated scroll can induce some serious discomfort.

I'm scratching my head trying to find a way around this. I suspect that there isn't one, but I'm hoping some God of Javascript here can suggest something. I'd really like to be able to use the space bar for this command.

2

There are 2 answers

0
gblazex On BEST ANSWER

Use document.documentElement.scrollTop = ... (and document.body in some browsers).

1
Hamish On

If you know where in the document you want to scroll to then you can simply use named anchors. Setting document.location to the anchor (e.g. #top, #div50 or whatever) should be very reliable.