jQuery OnLoad Page Scroll Issue

1.2k views Asked by At

I'm developing a website which involves the user being able to navigate to different parts of a page from other pages using # values in the address bar.

I have written a jQuery function to handle the scrolling here:

jQuery.fn.scrollToDiv = function(navheight)
{
    if (!navheight)
    {
        navheight = 30;
    }

    var offset = this.offset();
    var offsetTop = offset.top;
    var totalScroll = offsetTop-navheight-27;
    $('body,html').animate({
            scrollTop: totalScroll
    }, 500);
}

And I am calling the function in 2 different scenarios; when the user clicks a link where the object is on the current page, and when the user clicks a link that takes them to another page before scrolling to the element. See below:

When you are on the page:

$('.gotoPage').on('click', function(e)
{
    e.preventDefault();
    var sPath = window.location.pathname;
    var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
    if (sPath != '' && sPath != 'home')
    {
        var href = $(this).attr('href');

        handleScroll(href);
    }
});

and when you are not on the page:

$(document).ready(function(e) 
{    
    var target = window.location.hash;

    if (target != '')
    {
        $(target).scrollToDiv(30);
    }
});

It works perfectly when you are on the page and click the link, however when you're not on the page, it takes you to the subsequent page as you'd expect but it doesn't then scroll to the required element.

Let me know if you need any more information

Thanks in advance

EDIT: Added function handleScroll(target)

function handleScroll(target)
{
    if (target != '')
    {
        $(target).scrollToDiv(30);
    }
}
1

There are 1 answers

0
Ofir Baruch On BEST ANSWER

Following your comment:

I've noticed when refreshing the page is that it scrolls down then jumps back to the top of the page

It seems that your script does work, but something affecting it afterwards. I believe that there are some resources as additional css codes or images that aren't being taken in account when the scroll animation takes effect and since that function works by top offset - you must be sure that you're using it after all the resources that might affect the document's height or element's offset, are being loaded.

Therefore, instead of using your script in .ready(), use .load().

.ready() vs. .load()

In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code.

In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event instead.