question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Load different page and then smooth scroll within different page

See original GitHub issue

Hi, thanks for jquery-smooth-scroll. I think it is excellent.

I would like the smooth scrolling to take place on a different page. So my element on different-page.html looks like

<a href="/index.html#to-chapter1"> To Chapter 1</a>

I thought I can use the beforeScroll-function.

// smooth-scroll
$('a[href*=#]:not([href=#])').click(function() {
    $.smoothScroll({
        beforeScroll: function () {location.replace("/index.html");},
        offset: -120,
        scrollTarget: this.hash
    });
    return false;
});

However, smooth-scroll does not wait for the beforeScroll-function to be completed, i.e. the page to be loaded. Is there a way to make this happen? Thanks

Issue Analytics

  • State:closed
  • Created 9 years ago
  • Comments:11 (4 by maintainers)

github_iconTop GitHub Comments

3reactions
karlandcommented, May 12, 2014

@LL782 thanks a lot. It helped me to find the solution below together with two other sources: 1 and 2.

My final solution looks like that (tested under IE11, Firefox, Chrome, Opera, Safari):

$(document).ready(function() {

    var scrollnow = function(e) {
        // if scrollnow()-function was triggered by an event
        if (e) {
            e.preventDefault();
            var target = this.hash;
        }
        // else it was called when page with a #hash was loaded
        else {
            var target = location.hash;
        }

        // same page scroll
        $.smoothScroll({
            offset: -120,
            scrollTarget: target
        });
    };

    // if page has a #hash
    if (location.hash) {
        $('html, body').scrollTop(0).show();
        // smooth-scroll to hash
        scrollnow();
    }

    // for each <a>-element that contains a "/" and a "#"
    $('a[href*="/"][href*=#]').each(function(){
        // if the pathname of the href references the same page
        if (this.pathname.replace(/^\//,'') == location.pathname.replace(/^\//,'') && this.hostname == location.hostname) {
            // only keep the hash, i.e. do not keep the pathname
            $(this).attr("href", this.hash);
        }
    });

    // select all href-elements that start with #
    // including the ones that were stripped by their pathname just above
    $('a[href^=#]:not([href=#])').click(scrollnow);

});
1reaction
LL782commented, May 11, 2014

Hi, I did something like this and here are a couple of tips I can pass on.

Firstly, to prevent the browser from jumping straight to the target when the page loads you can add a suffix to all the scroll target ids, this stops them from immediately matching up with the hash from the address bar. So the target of page.html#target gets an id of target_hash rather than just target. Later some JS adds the suffix to the scrollTarget before triggering smoothScroll.

Secondly, I read that for browser compatibility reasons it’s worth putting in a short delay before testing the window.location for hash. And it’s also worth putting a short delay before executing the smoothScroll function. I don’t remember where I read this but the idea is to ensures the page is sufficiently loaded before executing the smoothScroll.

Putting that all together you end up with some code like this. It works for me on a number of sites.

// Requires SmoothScroll and jQuery
$(document).ready(function() {

    /* Take over default page anchor functionality */

    // Store hash location
    var hashLocation = false;
    if (location.hash) {
        hashLocation = window.location.hash;
        setTimeout(function() {
            hashLocation = window.location.hash;
        }, 1); // Execute at two moments for browser compatibility reasons
    }

    // If we have a hash location do stuff
    if (hashLocation) {

        // delay .1s for browser compatibility reasons
        setTimeout(function() {

            // Check hashLocation suffix
            if( hashLocation.indexOf('_hash') < 0 ) {
                hashLocation = hashLocation + "_hash";
            };

            // Scroll to target
            $.smoothScroll({
                scrollTarget: hashLocation
            });

        }, 100);

    };
});
Read more comments on GitHub >

github_iconTop Results From Across the Web

Smooth Scroll to DIV on Different Page using JavaScript & CSS
Learn how to redirect to a div on a different page with smooth scrolling by using CSS and JavaScript. We are solving a...
Read more >
Smooth Scroll Between pages JS | HWP Asset Library
when you click on a link in one page, if the link leads to an anchor in another page, this will will load...
Read more >
smooth scroll to another page anchor - jquery - Stack Overflow
This is my own solution, and it works : // == Smooth scroll to section == // $('header .navbar-nav > li > a,...
Read more >
Smooth scrolling to anchor on different page | TC
In this quick jQuery tutorial I'll show you how to smooth scroll to an anchor after its link was pressed on a different...
Read more >
How to Create Smooth Scrolling When Clicking an Anchor Link
Smooth scrolling allows jumping between page sections in just one click without manually scrolling up or down. To have this feature on your...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found