karlosuccess
karlosuccess

Reputation: 885

Smooth Scrolling To An Anchor in Another Page

I have figured how to smooth scroll from a link to an anchor but it is working in within the same page.

For example, if I am in the home page, this link will smooth scroll: mysite.com/#section

But if I am in the about page (mysite.com/about), the same link to the home page (mysite.com/#section) won't scroll smoothly, just the plain default.

I have this so far:

jQuery('a').click(function(){
    jQuery('html, body').animate({
        scrollTop: jQuery( this.hash ).offset().top
    }, 500);
});

I ran out of ideas, please help

Upvotes: 1

Views: 5323

Answers (3)

Skoua
Skoua

Reputation: 3603

Try this, checking if there's a #section in the URL and then scrolling to the target.

if(window.location.hash != '' && window.location.hash != '#') {
  let target = window.location.hash;

  if(!$(target).length) {
    return;
  }
  
  $('html, body').animate({
    scrollTop: $(target).offset().top
  });
}

if(!$(target).length) is important, you might get an error if there's no div with the right id on the page.

Upvotes: 0

karlosuccess
karlosuccess

Reputation: 885

Here is the code that worked for me in case someone is looking for the answer:

jQuery(document).ready(function() {

    // Scrolling for anchor links in within the same page
    jQuery('a[href*="#"]:not([href="#"])').click(function(){
        _hash = this.hash;
        _scroll_it( _hash );
    });

    // scrolling for anchor links coming from a different page
    var _hash = window.location.hash;
    if( _hash.length > 0 ){     
        window.scrollTo(0, 0);
        
        setTimeout( function() { 
            _scroll_it( _hash );
        }, 500 );       
    }
    
    function _scroll_it( _hash ){
        jQuery('html,body').animate({
            scrollTop: jQuery( _hash ).offset().top
        }, 500 );
    }

});

Upvotes: 1

Kip
Kip

Reputation: 513

You need to use CSS: Demo

html {
  scroll-behavior: smooth;
}

Upvotes: 2

Related Questions