I'll be honest, I'm way out of my depth here. I've created a pagination system where you click on a link it reloads the page and a certain number of list items are shown in an unordered list. When you click it again it'll reload the page and more items showing. Think how Twitter shows the tweets in your feed.
The problem is when it reloads the page it stays at the top. What I would like is for it to jump to the same position on the page it previously had.
I already have a selector for the link set up fine I just don't know how to get the current scroll position and then pass it to the new page for it to jump to.
Here's my code so far:
jQuery(document).ready(function(){
$("a[rel=more]").live("click", function(){
//script...
});
});
Where do I go from here?
Reload the items using AJAX instead of reloading the whole page.
Get and set the scroll position using
window.pageYOffset
andwindow.scrollTo(0, y)
.I'd store the position in the hash of the URL:
// after loading the document, scroll to the right position // maybe location.hash has to be converted to a number first $(document).ready(function() { window.scrollTo(0, location.hash); }); // I'm not quite sure if reload() does preserve the hash tag. location.hash = window.pageYOffset; location.reload();
As gs said add the elements via an ajax call instead of of reloading the page.
If you don't want to to use the jQuery.ScrollTo plugin. Which supports everything related to scrolling you could ever have dreamed about
I think what you need is just to pass an HTML anchor at the end of your link. The browser will scroll automatically to the element right next to the matched anchor. Example:
<a href="page2.html#myanchor">Next page</a>
At some point in the middle of page2:
<a name="myanchor">My item N</a>
according to @Shawn Grigson's link, pageYOffset is not supported the same across all browsers.
a jQuery solution (hopefully truly cross-browser compatible, though i haven't yet tested it) for getting and setting an element's vertical scroll is scrollTop().
来源:https://stackoverflow.com/questions/1022652/get-current-scroll-position-and-pass-it-as-a-variable-with-a-link