Scroll top function
-
I have written a very basic scroll to top function for use on pages that aren't topics (so /recent, custom pages etc). For the most part, this works fine. However, given that infinite scroll is being used, the
.container
div obviously changes as topics are added dynamically on scroll, even using something basic like the below "works" in the sense that it will scroll to the top, but then topics are being added meaning it's not "really" the top and I have to click the button again - sometimes 3-4 times depending on where I am.$(document).on("click", "#pageUp", function(e) { e.preventDefault(); $("html, body").animate({ scrollTop: 0 }, '300'); });
Is there any way around this where a return to the top of the page can be executed without the topics being loaded - for example, as though it was simply (for example) "/recent" being loaded for the first time etc.
-
Here is something that should work for topics list like recent/popular/category etc.
$(document).on("click", "#pageUp", function(e) { e.preventDefault(); const firstTopic = $('[component="category/topic"][data-index="0"]'); if (firstTopic.length) { $("html, body").animate({ scrollTop: 0 }, '300'); } else { ajaxify.refresh(); } });
The reason why you are seeing that behavior is because as you scroll down the page new topics are added at the bottom and old ones are removed from the top. To truly scroll all the way up you need to refresh the current page (or call
ajaxify.go(<current_page>);
), so it goes back to the top. If you haven't scrolled far enough down thendata-index="0"
will still be at the top, in this case you can just animate to the top and infinite scroll won't kick in. -