Home > OS >  Smooth Scrolling To An Anchor in Another Page
Smooth Scrolling To An Anchor in Another Page

Time:05-13

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

CodePudding user response:

You need to use CSS: Demo

html {
  scroll-behavior: smooth;
}

CodePudding user response:

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 - 200
  });
}

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

CodePudding user response:

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 );
    }

});

CodePudding user response:

<li >
    <a  href="#about">About</a>
</li>
jQuery('.link-scroll').each(function () {
    jQuery(this).on('click', () => {
        let targetID = jQuery(this).data('link');
        jQuery('html, body').animate({
            scrollTop: jQuery('#'   targetID).offset().top - 200
        });
    });
});

try this code for your solution.

  • Related