I modified a pretty common jQuery smooth-scroll method to suit my needs better --- a function to scroll to an anchor:
function scrollToAnchor(id, offset) {
target = $(id);
$('html, body').stop().animate({
'scrollTop': target.offset().top + offset}, 900, 'swing', function () {
window.location = id;
});
}
I have the offset
parameter to account for a fixed navigation pane at the top. I have the offset set to -100 on each call of scrollToAnchor
so that it scrolls 100 pixels less (this allows the content to be displayed without the fixed navigation pane hiding any content).
My issue occurs with window.location = id;
. This sets the URL to include the anchor, but because of this, it scrolls to the top of the div (this hides 100 pixels of content that my offset tries to prevent). I can't really use event.preventDefault()
because I don't have any event parameter. Is there any way to prevent the window from scrolling when I set the location?