0

I am having a url e.g. www.website.com/#divIdToScrollTo

Problem:

what I want here is on page load, the id following # will be extracted[which has already been mentioned as id of target div.]. And when the page is fully loaded the page should first stay at top and then smoothly start scrolling towards the div with a duration of say 5 seconds.

Current approach:

   var elem = $('#_' + window.location.hash.replace('#', ''));
    if(elem) {

         $('html, body').animate({
            scrollTop: $( elem ).offset().top
        }, 5000);
    }

My current solution extracts the id from the url and on page load is directly present at the target div. I am unable to see any smooth scrolling.

So, can I achieve the smooth scrolling I am looking for here. Please share your thoughts.[WITH CODE]

Kiran Dash
  • 4,816
  • 12
  • 53
  • 84

1 Answers1

2

You may have to consider using a url parameter instead of the hash fragment. If you are LOADING the page with the fragment on the URL, I believe it will automatically jump to that ID in the content, and I'm not sure if you can prevent that. There may be a hacky way to do it, by running something like:

$(document).ready(function(){
    // in order to "reset" back to the top
    $("html, body").scrollTop(0); 

   // and THEN run your animate scroll function here. 
}); 

Otherwise, the URL param approach I mentioned, you would have your URL look like this:

www.website.com/?section=aboutMe

And then in your code:

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"); 
    var results = regex.exec(location.search);

    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

var section = getParameterByName("section"); 

 $('html, body').animate({
        scrollTop: $( "#" + section ).offset().top
 }, 5000);

Grabbed the getParameterByName function from this thread: How can I get query string values in JavaScript?

Community
  • 1
  • 1
KDot
  • 496
  • 2
  • 7