简体   繁体   中英

Smooth scrolling to anchor on different page

I have searched up on Google how to smooth scroll to an anchor on a different page. I've tried a few of the methods, however, they don't seem to be working with the code I've already written up that works with smooth scrolling on one page.

Basically I've anchored my contact section on the index page and want my other pages to smooth scroll to that section when I click on the contact link on my nav bar. But at the moment all it does is jump straight to the anchor without scrolling from top.

This is my code:

$(document).ready(function() {
    $('a[href^="#"]').not("#quote-carousel a, ul.nav-pills a, div#accordian a").on("click", function(a) {
        a.preventDefault();
        var b = this.hash,
            c = $(b);
        $("html, body").stop().animate({
            scrollTop: c.offset().top - 50
        }, 900, "swing", function() {
            window.location.hash = b
        })
    })
});

You can start scrolling on hash change and when the page was loaded. So you can scroll to your target element and create a deep link also.

So the main difference between your approach and mine is, first change the hash (or do not prevent it) and listen for the hash change event.

This is how I do it:

JavaScript:

$(document).ready(function() {
    // check for hash when page has loaded
    if (getHash() != null) {
        checkForScrolling();
    }
});

// listen for hash change event here
window.onhashchange = function() {
    checkForScrolling();
};

// return hash if so or null if hash is empty
function getHash() {
    var hash = window.location.hash.replace('#', '');
    if (hash != '') {
        return hash;
    } else {
        return null;
    }
}

// this function handles your scrolling
function checkForScrolling() {
    // first get your element by attribute selector
    var elem = $('[data-anchor="' + getHash() + '"]');

    // cheeck if element exists
    if (elem.length > 0) {
        $('html, body').stop().animate({
            scrollTop: elem.offset().top
        }, 300);
    }
}

Working HTML Example:

<!DOCTYPE html>
<html>
    <head>
        <title>Smooth Scrolling</title>
        <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.4.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                // check for hash when page has loaded
                if (getHash() != null) {
                    checkForScrolling();
                }
            });
            // check for hash when hash has changed
            window.onhashchange = function() {
                checkForScrolling();
            };
            // return hash if so or null if hash is empty
            function getHash() {
                var hash = window.location.hash.replace('#', '');
                if (hash != '') {
                    return hash;
                } else {
                    return null;
                }
            }
            // this function handles your scrolling
            function checkForScrolling() {
                // first get your element by attribute selector
                var elem = $('[data-anchor="' + getHash() + '"]');
                // cheeck if element exists
                if (elem.length > 0) {
                    $('html, body').stop().animate({
                        scrollTop: elem.offset().top
                    }, 300);
                }
            }
        </script>
        <style type="text/css">
            body { font-family: Helvetica }
            section { position: relative; margin-bottom:10px; padding:20px; height: 300px; background-color: #eee; }
            section a { display:block; position: absolute; bottom: 10px; }
        </style>
    </head>
    <body>
        <div>
            <h1 data-anchor="start">Smooth Scrolling</h1>
            <ul>
                <li><a href="#1">Scroll to Anchor 1</a></li>
                <li><a href="#2">Scroll to Anchor 2</a></li>
                <li><a href="#3">Scroll to Anchor 3</a></li>
            </ul>
            <section>
                <h2 data-anchor="1">First Anchor</h2>
                <a href="#start">Back to top</a>
            </section>
            <section>
                <h2 data-anchor="2">Second Anchor</h2>
                <a href="#start">Back to top</a>
            </section>
            <section>
                <h2 data-anchor="3">Third Anchor</h2>
                <a href="#start">Back to top</a>
            </section>
        </div>
    </body>
</html>

Add following code on click of the anchor tag considering the html as follow

<div class="class_name"><a href="#contact">Contact</a></div>

Add code for above html

$(document).on('click', '.class_name a', function(e) {
            e.preventDefault();
            var target = $(this).attr('href'), $target = $(target); {
                $('html, body').stop().animate({
                    'scrollTop' : $target.offset().top - 50
                }, 900, 'swing', function() {
                    window.location.hash = target;
                });
            }
});

The above -50 value change depending on header height.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM