|
| 1 | +/** |
| 2 | + * NitroWebExpress™ — Scroll Position Preservation |
| 3 | + * Saves and restores scroll position across page reloads, form submissions, |
| 4 | + * and navigation within the same page. Uses sessionStorage keyed by URL path. |
| 5 | + * |
| 6 | + * Include in <head> or before </body> on any JSP page: |
| 7 | + * <script src="${pageContext.request.contextPath}/js/scroll-preserve.js"></script> |
| 8 | + * |
| 9 | + * MEARVK LLC — 2026 |
| 10 | + */ |
| 11 | +(function() { |
| 12 | + 'use strict'; |
| 13 | + |
| 14 | + var STORAGE_KEY = 'nwe-scroll-' + window.location.pathname; |
| 15 | + |
| 16 | + // Restore scroll position on page load |
| 17 | + function restoreScroll() { |
| 18 | + var saved = sessionStorage.getItem(STORAGE_KEY); |
| 19 | + if (saved) { |
| 20 | + var pos = JSON.parse(saved); |
| 21 | + window.scrollTo(pos.x, pos.y); |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + // Save scroll position |
| 26 | + function saveScroll() { |
| 27 | + var pos = { x: window.scrollX || window.pageXOffset, y: window.scrollY || window.pageYOffset }; |
| 28 | + try { |
| 29 | + sessionStorage.setItem(STORAGE_KEY, JSON.stringify(pos)); |
| 30 | + } catch (e) { /* sessionStorage full or unavailable */ } |
| 31 | + } |
| 32 | + |
| 33 | + // Save on scroll (debounced) |
| 34 | + var scrollTimer = null; |
| 35 | + window.addEventListener('scroll', function() { |
| 36 | + if (scrollTimer) clearTimeout(scrollTimer); |
| 37 | + scrollTimer = setTimeout(saveScroll, 150); |
| 38 | + }, { passive: true }); |
| 39 | + |
| 40 | + // Save before unload (navigation, reload, form submit) |
| 41 | + window.addEventListener('beforeunload', saveScroll); |
| 42 | + |
| 43 | + // Restore after DOM is ready |
| 44 | + if (document.readyState === 'complete' || document.readyState === 'interactive') { |
| 45 | + setTimeout(restoreScroll, 0); |
| 46 | + } else { |
| 47 | + document.addEventListener('DOMContentLoaded', restoreScroll); |
| 48 | + } |
| 49 | +})(); |
0 commit comments