Skip to content

Commit

Permalink
feat: account for scroll margin (#1197)
Browse files Browse the repository at this point in the history
  • Loading branch information
RostiMelk authored Sep 13, 2023
1 parent 3e2be26 commit 1c8a3cc
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,16 @@ const getOptions = (options: any): StandardBehaviorOptions => {
return { block: 'start', inline: 'nearest' }
}

const getScrollMargins = (target: Element) => {
const computedStyle = window.getComputedStyle(target)
return {
top: parseFloat(computedStyle.scrollMarginTop) || 0,
right: parseFloat(computedStyle.scrollMarginRight) || 0,
bottom: parseFloat(computedStyle.scrollMarginBottom) || 0,
left: parseFloat(computedStyle.scrollMarginLeft) || 0,
}
}

// Determine if the element is part of the document (including shadow dom)
// Derived from code of Andy Desmarais
// https://terodox.tech/how-to-tell-if-an-element-is-in-the-dom-including-the-shadow-dom/
Expand Down Expand Up @@ -127,14 +137,18 @@ function scrollIntoView<T = unknown>(
return
}

const margins = getScrollMargins(target)

if (isCustomScrollBehavior<T>(options)) {
return options.behavior(compute(target, options))
}

const behavior = typeof options === 'boolean' ? undefined : options?.behavior

for (const { el, top, left } of compute(target, getOptions(options))) {
el.scroll({ top, left, behavior })
const adjustedTop = top - margins.top + margins.bottom
const adjustedLeft = left - margins.left + margins.right
el.scroll({ top: adjustedTop, left: adjustedLeft, behavior })
}
}

Expand Down

0 comments on commit 1c8a3cc

Please sign in to comment.