Skip to content

Commit

Permalink
improve and simplify auto scrolling
Browse files Browse the repository at this point in the history
  • Loading branch information
tztsai committed Nov 12, 2024
1 parent d634c21 commit e3a3722
Showing 1 changed file with 10 additions and 13 deletions.
23 changes: 10 additions & 13 deletions content/mdwise.js
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ var makeFoldable = (selector = 'h1, h2, h3, h4, h5') => {
var focusedDetails;
var scrollLock = false;

var focusOnDetails = (details, scroll = 'follow') => {
var focusOnDetails = (details) => {
if (
scrollLock && focusedDetails
&& findNext(details) !== focusedDetails
Expand All @@ -247,29 +247,26 @@ var focusOnDetails = (details, scroll = 'follow') => {
for (p = details.parentElement; p.tagName !== 'BODY'; p = p.parentElement) {
if (p.tagName === 'DETAILS') p.open = true;
}
focusedDetails = details;

setTimeout(() => { scrollLock = false; }, 500);

if (scroll == 'center') {
return details.scrollIntoView({ behavior: 'smooth', block: 'center' });
}

const rect2 = details.getBoundingClientRect();

// keep the top of the section at the same position
var dy = 0;
if (rect2.top < rect1.top && details.firstChild.firstChild.tagName === 'H2') {
dy += rect2.bottom - rect1.top - 30;
focusedDetails = details.lastChild.lastChild;
}
else if (rect2.bottom > window.innerHeight) {
dy += Math.min(rect2.top, rect2.bottom - window.innerHeight);
if ((!focusedDetails || rect2.top < rect1.top) &&
details.firstChild.firstChild.tagName === 'H2') {
dy += Math.min(rect2.top, rect2.height) - 10;
}
// else if (rect2.bottom > window.innerHeight) {
// dy += Math.min(rect2.top, rect2.bottom - window.innerHeight + 10);
// }

if (Math.abs(dy) > 200) {
if (Math.abs(dy) > 50) {
window.scrollBy({ top: dy, behavior: 'smooth' });
} else scrollLock = false;

focusedDetails = details;
}

function findNext(elm) {
Expand Down

0 comments on commit e3a3722

Please sign in to comment.