I am using this code to scroll the page after clicking a button:
$(document).ready(function() {
$("#button").click(function(e) {
e.preventDefault();
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 8000);
});
});
But I want to make it work without clicking any button. When the page loads, it should scroll. I used this code and it does not work:
$(document).ready(function() {
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 8000);
});
I personally am not a big fan of using jQuery's animate function, so i implemented my own. You can change the speed of it by increasing or decreasing the time of the setTimeout function.
Here is a link to the fiddle that i made to demonstrate what I think you are trying to do. Let me know if this helps!
https://jsfiddle.net/ogb4t33q/
In this block:
this
will refer to document. That was OK in the other version of your function, becausethis
referred to an<a>
element withhref
. That allowed$($.attr(this, 'href'))
to find an element and complete the logic to scroll there.You'll either need to define exactly the element you want to scroll to like this:
Or work with
window.location.hash
to read the#...
value from the URL.