/ Published in: JavaScript
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
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
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
(function (window, undefined) { if (!window.localStorage) { if (window.console) { console.info('xybookmark cannot access localStorage'); return; } } var LS = window.localStorage; var xyb = { lsname : 'LS_XYB', list : [], load : function () { this.list = LS.getItem(this.lsname) ? JSON.parse(LS.getItem(this.lsname)) : []; }, find : function (url) { for (var i = 0, ll = this.list.length; i < ll; i++) { var entry = this.list[i]; if (entry.url === url) { return i; } } return -1; }, save : function (url) { var title = document.getElementsByTagName('title')[0].innerHTML; this.list.push({ title : title, url : url, timestamp : Date.now(), scrollY : window.scrollY, scrollX : window.scrollX }); }, commit : function () { LS.setItem(this.lsname, JSON.stringify(this.list)); }, onWindowKeyDown : function (e) { if (e.keyCode === 66 /*m*/ && e.shiftKey && e.ctrlKey) this.bookmark(); }, scrollTo : function () { var idx = this.find(window.location.href); if (idx > -1) { var item = this.list[idx]; window.scrollTo(item.scrollX, item.scrollY); } }, bookmark : function () { var url = window.location.href; var idx = this.find(url); if (idx > -1) { this.list[idx].scrollX = window.scrollX; this.list[idx].scrollY = window.scrollY; } else { this.save(url); } this.commit(); }, remove : function () { var idx = this.find(window.location.href); if (idx > -1) { this.list.splice(idx, 1); } this.commit(); }, reset : function () { this.list = []; LS.removeItem(this.lsname); } }; xyb.load(); xyb.scrollTo(); window.addEventListener('keydown', xyb.onWindowKeyDown.bind(xyb)); window.XYB = window.XYB || { addBookmark : xyb.bookmark.bind(xyb), removeBookmark : xyb.remove.bind(xyb), reset : xyb.reset.bind(xyb) }; })(window);
URL: https://github.com/andreasi/xybookmark