Handling scrolling of long articles on a blog


/ Published in: JavaScript
Save to your folder(s)

xybookmark is a lightweight JavaScript library that allows the readers of a blog to boomark the scroll position of a long article.
More specifically it saves the scrollX and scrollY state of a page so that when the user revisits the url, the page scrolls down or right to the position that was bookmarked. xybookmark uses localStorage to save the urls of a website


Copy this code and paste it in your HTML
  1. (function (window, undefined) {
  2.  
  3. if (!window.localStorage) {
  4. if (window.console) {
  5. console.info('xybookmark cannot access localStorage');
  6. return;
  7. }
  8. }
  9.  
  10.  
  11. var LS = window.localStorage;
  12.  
  13. var xyb = {
  14. lsname : 'LS_XYB',
  15. list : [],
  16. load : function () {
  17. this.list = LS.getItem(this.lsname) ? JSON.parse(LS.getItem(this.lsname)) : [];
  18. },
  19. find : function (url) {
  20. for (var i = 0, ll = this.list.length; i < ll; i++) {
  21. var entry = this.list[i];
  22. if (entry.url === url) {
  23. return i;
  24. }
  25. }
  26. return -1;
  27. },
  28. save : function (url) {
  29. var title = document.getElementsByTagName('title')[0].innerHTML;
  30. this.list.push({
  31. title : title,
  32. url : url,
  33. timestamp : Date.now(),
  34. scrollY : window.scrollY,
  35. scrollX : window.scrollX
  36. });
  37. },
  38. commit : function () {
  39. LS.setItem(this.lsname, JSON.stringify(this.list));
  40. },
  41. onWindowKeyDown : function (e) {
  42. if (e.keyCode === 66 /*m*/
  43. && e.shiftKey && e.ctrlKey)
  44. this.bookmark();
  45. },
  46. scrollTo : function () {
  47. var idx = this.find(window.location.href);
  48. if (idx > -1) {
  49. var item = this.list[idx];
  50. window.scrollTo(item.scrollX, item.scrollY);
  51. }
  52. },
  53. bookmark : function () {
  54. var url = window.location.href;
  55. var idx = this.find(url);
  56. if (idx > -1) {
  57. this.list[idx].scrollX = window.scrollX;
  58. this.list[idx].scrollY = window.scrollY;
  59. } else {
  60. this.save(url);
  61. }
  62. this.commit();
  63. },
  64. remove : function () {
  65. var idx = this.find(window.location.href);
  66. if (idx > -1) {
  67. this.list.splice(idx, 1);
  68. }
  69. this.commit();
  70. },
  71. reset : function () {
  72. this.list = [];
  73. LS.removeItem(this.lsname);
  74. }
  75. };
  76.  
  77. xyb.load();
  78. xyb.scrollTo();
  79. window.addEventListener('keydown', xyb.onWindowKeyDown.bind(xyb));
  80.  
  81. window.XYB = window.XYB || {
  82. addBookmark : xyb.bookmark.bind(xyb),
  83. removeBookmark : xyb.remove.bind(xyb),
  84. reset : xyb.reset.bind(xyb)
  85. };
  86.  
  87. })(window);

URL: https://github.com/andreasi/xybookmark

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.