Prevent scrolling when closing modals
Prevent scrolling when re-focusing the modal-triggering element once the modal was hidden. Closes #35391.
I wasn't able to reproduce my issue on Codepen, but you can on the Bootstrap documentation page:
- Go to https://getbootstrap.com/docs/5.1/getting-started/introduction/ and scroll down a few lines
- Click on the "Search docs" input at the top of the page
- 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.
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.
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).
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 :)
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.
Yeah, so this is a test for sure...
@smares can you add a test please, to get this MR moving?
I believe it is fine to check something like, offesetTop before & after