bootstrap icon indicating copy to clipboard operation
bootstrap copied to clipboard

Prevent scrolling when closing modals

Open smares opened this issue 4 years ago • 7 comments

Prevent scrolling when re-focusing the modal-triggering element once the modal was hidden. Closes #35391.

smares avatar Nov 23 '21 19:11 smares

I wasn't able to reproduce my issue on Codepen, but you can on the Bootstrap documentation page:

  1. Go to https://getbootstrap.com/docs/5.1/getting-started/introduction/ and scroll down a few lines
  2. Click on the "Search docs" input at the top of the page
  3. Hit the Tab key for the focus to move to the Bootstrap version picker on the right

Notice how once you finish step 3, the page scrolls a few lines upward although it makes no sense as the navbar is sticky and always visible anyway. The exact same thing happens if you were to have a modal triggering element in the navbar that receives focus once you close the modal.

smares avatar Nov 23 '21 20:11 smares

I don't think it relates to the script then. If I recall correctly, the scroll issue with the search in our docs is caused by the CSS scroll-padding-top property being used.

Preventing scroll when restoring focus would probably help I guess, but without a reduced test case that's hard to say.

ffoodd avatar Nov 24 '21 06:11 ffoodd

Thanks, that was it! Your hint about scroll-padding-top allowed me to create a pen showing the issue: https://codepen.io/smares/pen/MWvMjEz Scroll a few lines down, then click on the "Open modal" button, then close the modal -> the page scrolls up.

And this shows the effect of the change simulated by two buttons - one has preventScroll, the other does not: https://codepen.io/smares/pen/ExvBgQq (scroll to the bottom).

smares avatar Nov 24 '21 09:11 smares

Your patch does not solve the docs issue, though: https://deploy-preview-35393--twbs-bootstrap.netlify.app/docs/5.1/getting-started/introduction/

Also, without a test, this is a little moot and it's bound to happen again :)

XhmikosR avatar Nov 24 '21 12:11 XhmikosR

The patch should not solve the docs issue, that is something else. The patch solves the issue where closing a modal re-focuses its trigger causing a page scroll. Re-focusing should no longer scroll the page with this patch.

smares avatar Nov 24 '21 13:11 smares

Yeah, so this is a test for sure...

XhmikosR avatar Nov 24 '21 15:11 XhmikosR

@smares can you add a test please, to get this MR moving?

I believe it is fine to check something like, offesetTop before & after

GeoSot avatar Feb 03 '22 16:02 GeoSot