You are here

24 May 2011
Getting and save window scroll position with jQuery. You also need cookie plugin to store the position value in cookies, so it can be used after browser page changes.
Use this jQuery plugin for storing cookies. If you use it on your site then make sure you get the minified version.

Javascript Cookie Library with jQuery bindings and JSON support
If you press on a link that has link-class as class, then page scroll position remains the same on the next page you enter. It has to be your site, where our script is included.
Source code viewer
  1. (function($){$().ready(function(){
  2.  
  3. $.cookies.get('myCookie');
  4.  
  5. // Set window scroll position if cookie is set.
  6. window.scroll(0, $.cookies.get('myCookie'));
  7. // Unset cookie after setting scroll position.
  8. $.cookies.del('myCookie');
  9.  
  10. // Make this class objects keep page scroll position.
  11. $('.link-class').each(function(){
  12. $(this).click(function() {
  13. $.cookies.set('myCookie', getPageScroll());
  14. });
  15. });
  16.  
  17. });})(jQuery);
  18.  
  19.  
  20. // This function simply gets the window scroll position, works in all browsers.
  21. function getPageScroll() {
  22. var yScroll;
  23. if (self.pageYOffset) {
  24. yScroll = self.pageYOffset;
  25. } else if (document.documentElement && document.documentElement.scrollTop) {
  26. yScroll = document.documentElement.scrollTop;
  27. } else if (document.body) {
  28. yScroll = document.body.scrollTop;
  29. }
  30. return yScroll;
  31. }
Programming Language: Javascript