Skip to content

Commit

Permalink
Allow preventing scroll when an element is focused
Browse files Browse the repository at this point in the history
  • Loading branch information
krksgbr committed Feb 20, 2024
1 parent 0f9ad4b commit 4c6aaf8
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 1 deletion.
24 changes: 24 additions & 0 deletions cypress/e2e/spec.cy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,4 +201,28 @@ describe("focus-shift spec", () => {
{ eventType: "keydown", selector: "#button-3", options: keyevent({ key: "ArrowDown", repeat: false }) }
])
)

it("allows preventing scroll", function () {
cy.visit("./cypress/fixtures/scroll.html")
function testScroll(id, assert) {
cy.window()
.its("scrollX")
.then((scrollXBefore) => {
const firstButton = cy.get(id)
firstButton.focus()
firstButton.trigger("keydown", keyevent({ key: "ArrowRight" }))
cy.window()
.its("scrollX")
.then((scrollXAfter) => {
assert(scrollXBefore, scrollXAfter)
})
})
}
testScroll("#prevent", function (before, after) {
expect(before).to.equal(after)
})
testScroll("#no-prevent", function (before, after) {
expect(before).to.not.equal(after)
})
})
})
20 changes: 20 additions & 0 deletions cypress/fixtures/scroll.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<div class="nav-group" style="display: flex; gap: 100vw">
<div><button id="prevent">First Button</button></div>
<div><button data-focus-preventScroll>Don't scroll here</button></div>
</div>

<div class="nav-group" style="display: flex; gap: 100vw" id="no-prevent-scroll">
<div><button id="no-prevent">First Button</button></div>
<div><button>Scroll Here</button></div>
</div>
<script src="../../index.js"></script>
</body>
</html>
3 changes: 2 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,8 @@ function applyFocus(direction, origin, target) {
if (isGroup(target)) {
dispatchGroupFocus(direction, origin, target)
} else if ("focus" in target && typeof target.focus === "function") {
target.focus()
const preventScroll = target.hasAttribute("data-focus-preventScroll")
target.focus({ preventScroll: preventScroll })
}
}

Expand Down

0 comments on commit 4c6aaf8

Please sign in to comment.