Robel Tech πŸš€

Prevent body scrolling but allow overlay scrolling

February 20, 2025

πŸ“‚ Categories: Css
🏷 Tags: Overlay Lightbox
Prevent body scrolling but allow overlay scrolling

Creating a seamless person education is paramount successful net improvement. 1 communal situation includes managing scroll behaviour once an overlay seems. Customers ought to beryllium capable to work together with the overlay contented with out unintentionally scrolling the underlying leaf. This article dives into the strategies for stopping assemblage scrolling piece permitting scrolling inside an overlay, enhancing person action and general web site usability. We’ll research the “forestall assemblage scrolling however let overlay scrolling” resolution with applicable examples and codification snippets.

Knowing the Situation

Ideate a modal popping ahead, displaying important accusation oregon prompting person enter. Arsenic the person scrolls done the modal contented, the inheritance leaf scrolls on, creating a jarring and disorienting education. This happens due to the fact that the scroll case is by default utilized to the full papers. Our end is to isolate this scroll behaviour to the overlay.

This content is peculiarly prevalent connected cell units wherever surface existent property is constricted and unintended scrolling tin easy happen. Addressing this situation improves accessibility and contributes to a much polished and nonrecreational person education.

By implementing the correct methods, we tin make a smoother, much intuitive action, permitting customers to direction connected the overlay contented with out distractions.

CSS Strategies for Scroll Power

CSS gives a simple attack to controlling scroll behaviour. The overflow: hidden; place utilized to the assemblage component efficaciously prevents scrolling of the underlying leaf. Nevertheless, this besides prevents scrolling inside the overlay. To code this, we mark the overlay component particularly and fit its overflow-y: car; place. This permits scrolling lone inside the overlay’s contented country.

Present’s a elemental illustration:

css assemblage.modal-unfastened { overflow: hidden; } .modal-contented { overflow-y: car; } This codification snippet makes use of a people, “modal-unfastened,” added to the assemblage once the modal is progressive. This focused attack ensures that the overflow: hidden is utilized lone once essential, preserving average scrolling behaviour elsewhere connected the tract.

JavaScript for Dynamic Scroll Direction

Piece CSS supplies a coagulated instauration, JavaScript gives larger flexibility for dynamic eventualities. We tin usage JavaScript to shop the assemblage’s scroll assumption earlier beginning the modal and reconstruct it upon closing. This preserves the person’s assumption connected the underlying leaf, enhancing the general person education.

javascript fto scrollPosition = zero; relation openModal() { scrollPosition = framework.pageYOffset; papers.assemblage.kind.overflow = ‘hidden’; papers.assemblage.kind.assumption = ‘mounted’; papers.assemblage.kind.apical = -${scrollPosition}px; // … another modal beginning logic } relation closeModal() { papers.assemblage.kind.overflow = ‘’; papers.assemblage.kind.assumption = ‘’; papers.assemblage.kind.apical = ‘’; framework.scrollTo(zero, scrollPosition); // … another modal closing logic } This attack makes use of the pageYOffset place to seizure and reconstruct scroll assumption. The assumption: mounted and calculated apical worth guarantee the inheritance stays visually static piece the modal is unfastened.

Cell-Archetypal Issues

Connected cellular units, stopping assemblage scrolling down overlays is important for usability. Contact interactions tin inadvertently set off inheritance scrolling, creating a irritating education. The CSS and JavaScript strategies mentioned earlier are as relevant and indispensable for cellular optimization. See utilizing contact-circumstantial occasions for equal finer power.

Abbreviated, concise paragraphs are particularly crucial connected cell to heighten readability and accommodate smaller screens. Guarantee your overlay contented is easy digestible and navigable connected assorted units. Trial completely connected antithetic cell browsers and working techniques to guarantee accordant show.

  • Usage overflow: hidden connected the assemblage.
  • Use overflow-y: car oregon overflow-x: car (oregon some) to the overlay contented.

Precocious Strategies and Libraries

For analyzable eventualities oregon bigger initiatives, using JavaScript libraries tin streamline the procedure. Libraries similar assemblage-scroll-fastener message pre-constructed features and grip border instances, simplifying implementation and enhancing transverse-browser compatibility. These libraries tin beryllium invaluable for tasks requiring sturdy scroll direction options.

Moreover, see incorporating accessibility options. Guarantee direction direction inside the overlay is decently applied truthful keyboard customers tin navigate seamlessly. Supply broad ocular cues and due ARIA attributes to heighten the education for customers with disabilities.

  1. Instal a room similar assemblage-scroll-fastener.
  2. Mark the scrollable component inside your overlay.
  3. Disable assemblage scrolling once the overlay is unfastened and re-change it once closed.

Infographic Placeholder: Illustrating the steps of implementing scroll locking with ocular immunodeficiency.

Larn much astir person education champion practices.Outer sources:

By stopping assemblage scrolling piece permitting overlay scrolling, you heighten person direction, better navigation, and make a much polished internet education. Whether or not you take CSS, JavaScript, oregon a devoted room, implementing these strategies is a invaluable measure successful optimizing web site usability and accessibility. See the circumstantial wants of your task and take the technique that champion fits your necessities. This seemingly insignificant item tin importantly contact person restitution and lend to a much nonrecreational and person-affable web site. Research the supplied assets and experimentation with antithetic strategies to detect the optimum resolution for your initiatives. Retrieve to prioritize person education and attempt for seamless interactions successful all facet of your internet improvement endeavors.

FAQ

Q: What if the overlay contented is longer than the viewport?

A: The overflow-y: car place volition change scrolling inside the overlay, permitting customers to entree each of the contented, equal if it exceeds the available country.

Q: Are location show issues once utilizing JavaScript for scroll direction?

A: Piece the supplied JavaScript strategies are mostly performant, it’s ever a bully pattern to trial and optimize your codification for antithetic gadgets and browsers, peculiarly connected older oregon little almighty units.

Question & Answer :
I’ve been looking out for a “lightbox” kind resolution that permits this however haven’t recovered 1 but (delight, propose if you cognize of immoderate).

The behaviour I’m making an attempt to recreate is conscionable similar what you’d seat astatine Pinterest once clicking connected an representation. The overlay is scrollable (arsenic successful the entire overlay strikes ahead similar a leaf connected apical of a leaf) however the assemblage down the overlay is mounted.

I tried to make this with conscionable CSS (i.e. a div overlay connected apical of the entire leaf and assemblage with overflow: hidden), however it doesn’t forestall div from being scrollable.

However to support the assemblage/leaf from scrolling however support scrolling wrong the fullscreen instrumentality?

Explanation

Wanting astatine actual implementation of the pinterest tract (it mightiness alteration successful the early), once you unfastened the overlay, a noscroll people is utilized to the assemblage component (mounting overflow: hidden) making the assemblage nary longer scrollable.

The overlay created connected-the-alert oregon already injected successful the leaf and made available by way of show: artifact β€” it makes nary quality – has assumption : mounted and overflow-y: scroll, with apical, near, correct and bottommost properties fit to zero: this kind makes the overlay enough the entire viewport (however present we are successful 2022, truthful you whitethorn usage inset: zero alternatively).

The div wrong the overlay is successful assumption: static truthful the vertical scrollbar is associated to that component. This is ensuing successful a scrollable however fastened overlay.

Once you adjacent the overlay, you person to fell it (utilizing show: no) and you might equal distance the node through javascript (oregon conscionable the contented wrong, it’s ahead to you however besides relies upon connected the quality of the contented).

The last measure is to besides distance the noscroll people utilized to the assemblage (truthful the overflow place will get backmost to the worth it had antecedently)


Codification

Codepen Illustration

(it plant by altering the aria-hidden property of the overlay successful command to entertainment and fell it and to addition its accessibility).

Markup
(unfastened fastener)

<fastener kind="fastener" people="unfastened-overlay">Unfastened Bed</fastener> 

(overlay and adjacent fastener)

<conception people="overlay" aria-hidden="actual" tabindex="-1"> <div> <h2>Hullo, I'm the overlayer</h2> ... <fastener kind="fastener" people="adjacent-overlay">Adjacent Bed</fastener> </div> </conception> 

CSS

.noscroll { overflow: hidden; } .overlay { assumption: mounted; overflow-y: scroll; inset: zero; } [aria-hidden="actual"] { show: no; } [aria-hidden="mendacious"] { show: artifact; } 

Javascript (vanilla-JS)

var assemblage = papers.assemblage, overlay = papers.querySelector('.overlay'), overlayBtts = papers.querySelectorAll('fastener[people$="overlay"]'), openingBtt; [].forEach.call(overlayBtts, relation(btt) { btt.addEventListener('click on', relation() { /* Observe the fastener people sanction */ var overlayOpen = this.className === 'unfastened-overlay'; /* storing a mention to the beginning fastener */ if (overlayOpen) { openingBtt = this; } /* Toggle the aria-hidden government connected the overlay and the nary-scroll people connected the assemblage */ overlay.setAttribute('aria-hidden', !overlayOpen); assemblage.classList.toggle('noscroll', overlayOpen); /* Connected any cellular browser once the overlay was antecedently opened and scrolled, if you unfastened it once more it doesn't reset its scrollTop place */ overlay.scrollTop = zero; /* forcing direction for Assistive applied sciences however line: - if your modal has conscionable a construction and a fastener decision the direction connected the fastener - if your modal has a agelong matter wrong (e.g. a privateness argumentation) decision the direction connected the archetypal heading wrong the modal - other conscionable direction the modal. Once you adjacent the overlay reconstruct the direction connected the fastener that opened the modal. */ if (overlayOpen) { overlay.direction(); } other { openingBtt.direction(); openingBtt = null; } }, mendacious); }); /* observe Flight cardinal once the overlay is unfastened */ papers.assemblage.addEventListener('keyup', (ev) => { if (ev.cardinal === "Flight" && overlay.getAttribute('aria-hidden') === 'mendacious') { overlay.setAttribute('aria-hidden', 'actual'); assemblage.classList.toggle('noscroll', mendacious); openingBtt.direction(); openingBtt = null; } }) 

Eventually, present’s different illustration successful which the overlay opens with a slice-successful consequence by a CSS modulation utilized to the opacity place. Besides a padding-correct is utilized to debar a reflow connected the underlying matter once the scrollbar disappears.

Codepen Illustration (slice)

CSS

.noscroll { overflow: hidden; } @media (min-instrumentality-width: 1025px) { /* not strictly essential, conscionable an experimentation for this circumstantial illustration and couldn't beryllium essential astatine each connected any browser */ .noscroll { padding-correct: 15px; } } .overlay { assumption: mounted; overflow-y: scroll; inset: zero; } [aria-hidden="actual"] { modulation: opacity 1s, z-scale 0s 1s; width: 100vw; z-scale: -1; opacity: zero; } [aria-hidden="mendacious"] { modulation: opacity 1s; width: one hundred%; z-scale: 1; opacity: 1; }