Reputation: 2063
I have created a WordPress site with a custom pagination function. The function add's #latest onto the end of the link to target my websites div with the latest posts in. For example if a user clicks on page 3 it will load the page and then send them to the div #latest. This works fine however I would like for it to smoothly scroll to the div.
I tried adding this jQuery and nothing happened, it still just abruptly goes to the section.
jQuery(document).ready(function(){
jQuery('a[href^="#"]').on('load',function (e) {
e.preventDefault();
var target = this.hash;
var $target = $(target);
jQuery('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing', function () {
window.location.hash = target;
});
});
});
Is there a better way of doing this?
Upvotes: 0
Views: 3344
Reputation: 2624
This is how I do it with only javascript:
if (window.location.hash) {
var hash = window.location.hash;
var element = document.querySelector(hash);
if (element)
element.scrollIntoView({
behavior: "smooth",
block: "nearest",
inline: "start",
});
}
Upvotes: 0
Reputation: 544
I believe the animate function is running before the target is being assigned. I would use promises to solve this.
var target = $.deferred;
target.resolve("latest");
$.when(target).done(function scrollTo(where){
$('html, body').animate({
scrollTop: $('#'+where).offset().top
}, 900,'swing');
return false;
});
Upvotes: 0
Reputation: 2131
I believe that there are some resources that aren't being taken in account when the scroll animation takes effect and since that function works by top offset - you must be sure that you're using it after all the resources that might affect the document's height or element's offset, are being loaded.
Change your ready
to load
.
In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code.
In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event instead.
Here is my function:
$(function(){
var target = "latest";
$('html, body').animate({
scrollTop: $('#'+target).offset().top
}, 900,'swing');
return false;
});
Upvotes: 5