Search code examples
javascriptgetelementbyidjs-scrollintoview

Automatically scroll to a specific part of the home (root) page from a separate url back link


I have this base code on my website's home page (myexample.com):

setTimeout(function(){
  document.getElementById("pizza3").scrollIntoView( {behavior: 'smooth'} );
}, 2000);

Now as it stands, the scrolling effect will fire on every call to the home page (myexample.com). I actually want this script snippet to fire, AND ONLY FIRE, when the home page's url string explicitly reads: myexample.com#pizza3

How might the base code be modified to achieve?

Cheers!


Solution

  • This should catch the last 7 digits of your URL and check them for the pizza tag:

    let url = window.location.href;
    let tagStr = url.substr(url.length - 7);
    if (tagStr == '#pizza3') {
    
    setTimeout(function(){
        document.getElementById("pizza3").scrollIntoView( {behavior: 'smooth'} );
    }, 2000);
          }