Been asked a dozen times, but no luck from what I've read. Prevent Anchor Jumping on page load

Posted by jasenmp on Stack Overflow See other posts from Stack Overflow or by jasenmp
Published on 2013-10-18T15:50:55Z Indexed on 2013/10/18 15:53 UTC
Read the original article Hit count: 192

Filed under:

I'm currently working with WP theme that can be found here: sanjay.dmediastudios.com

I'm currently using 'smooth scroll' on my page, I'm attempting to have the page smoothly scroll to the requested section when coming from an external link (for instance coming from the blog page takes you to sanjay.dmediastudios.com/#portfolio) from there I want the page to start at the top and THEN scroll to the portfolio section.

What's happening is it briefly displays the 'portfolio section' (anchor jump) and THEN resets to the top and scrolls down. It's driving me nuts :(.

Here is the code I'm using:

Click function for smooth scroll:

        $(function() {

        $('.menu li a').click(function() {
            if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
                var target = $(this.hash);
                target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
                if (target.length) {
                    $root.animate({
                        scrollTop: target.offset().top - 75
                    }, 800, 'swing');
                    return false;
                }
            }
        });
        //end of click function
    });

The page load function:

$(window).on("load", function() {
        if (location.hash) { // do the test straight away
            window.scrollTo(0, 0); // execute it straight away
            setTimeout(function() {
                window.scrollTo(0, 0); // run it a bit later also for browser compatibility
            }, 1);
        }
        var urlHash = window.location.href.split("#")[1];
        if (urlHash && $('#' + urlHash).length)
            $('html,body').animate({
                scrollTop: $('#' + urlHash).offset().top - 75
            }, 800, 'swing');

    });

Any help would be MUCH appreciated.

© Stack Overflow or respective owner

Related posts about jQuery