Skip to content

Commit

Permalink
fix(modal): prevent body scrolling when open (fix #2)
Browse files Browse the repository at this point in the history
  • Loading branch information
balsigergil committed Jan 26, 2024
1 parent fca4f34 commit 725b847
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
10 changes: 10 additions & 0 deletions src/modal/Modal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export class Modal extends HTMLElement {
this.classList.add("bl-modal");
this.role = "dialog";
this.ariaModal = "false";
this.style.display = "none";
const modalWrapper = document.createElement("div");
modalWrapper.classList.add("bl-modal-wrapper");

Expand Down Expand Up @@ -96,6 +97,11 @@ export class Modal extends HTMLElement {
this.#sourceElement = sourceElement;
this.style.display = "flex";
this.ariaModal = "true";

// Prevent scrolling of the body
document.body.style.overflow = "hidden";

// Trick to make the transition work
setTimeout(() => this.classList.add("open"), 0);
const focusableElements = this.querySelectorAll<HTMLElement>(
"a, button, input, textarea, select, details, [tabindex]:not([tabindex='-1'])",
Expand All @@ -110,6 +116,10 @@ export class Modal extends HTMLElement {
close() {
this.classList.remove("open");
this.ariaModal = "false";

// Restore scrolling of the body
document.body.style.overflow = "auto";

setTimeout(() => (this.style.display = "none"), 150);
if (this.#sourceElement) {
this.#sourceElement.focus();
Expand Down
1 change: 0 additions & 1 deletion src/modal/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
inset: 0;
width: 100%;
height: 100%;
display: none;
justify-content: center;
align-items: flex-start;
overflow-x: hidden;
Expand Down

0 comments on commit 725b847

Please sign in to comment.