views:

28

answers:

1

Hi folks,

I have a piece of jQuery code which - in theory - scrolls down to a specific part of the window depending on what's after the hash in the URL tag (myaddress.html#wheretoscroll).

The code called is this:

$(document).ready(function() {
    anchor = unescape(self.document.location.hash.substring(1))
    if (anchor) {
        $.scrollTo('#anchor-' + anchor, 500, {offset:-150});
    }
}

The problem is that the document scrolls to a place well out of its intended alignment. It gets anchors near the top almost right, but seems to scroll too far down with increasing inaccuracy as the document goes down.

However...

If I run the same code inside a .click or .hover function, for example:

$(document).ready(function() {
    $('body').hover(function() {
        anchor = unescape(self.document.location.hash.substring(1))
        if (anchor) {
            $.scrollTo('#anchor-' + anchor, 500, {offset:-150});
        }
    });
});

it scrolls to the exact location it should be. I'm assuming this is some sort of problem with the DOM not being read correctly at the point of .ready? Any suggestions for correcting this (or a more elegant way of triggering the action as soon as the page loads but not directly through .ready) would be much appreciated.

If it matters, the .scrollTo plugin I'm using can be found here: http://flesler.blogspot.com/2007/10/jqueryscrollto.html

Cheers...

+2  A: 

Try this instead:

$(window).load(function() {
    anchor = unescape(self.document.location.hash.substring(1))
    if (anchor) {
        $.scrollTo('#anchor-' + anchor, 500, {offset:-150});
    }
}

Parts of your page are continuing to load after the DOM is ready. $(window).load() fires when all your content is loaded -- including images.

Ken Redler
Specifying height and width of images is probably also a solution
sunn0
@sunn0, true, good point -- assuming it's only images and he(?) knows the dimensions in advance.
Ken Redler
You may want to wrap that up in a setTimeout that will get cleared if the user starts scrolling. That way, the page won't jump around like crazy.
AutoSponge
Perfect - thankyou. ;-)
unclaimedbaggage