Reputation: 89
On my portfolio, I map over an array of projects that are rendered one after the next. Each project then has a button that opens a modal. The problem is if I open the modal on one project, scroll down, close the modal, and then open the modal on another project, this second modal will start at the same location the first one was closed.
It seems the issue has to do with where the modal is placed in the codebase, at the level where I initially map over the projects array and at the child level of a project.
window.scrollTo(0, 0)
AND OR
let getThisEle = document.getElementsByClassName('example') getThisEle.scrollTop = 0
do not work.
Upvotes: 1
Views: 1971
Reputation: 746
For me scrollTop
works when setting it after showing the dialog:
const dialog = document.querySelector("dialog");
dialog.showModal();
dialog.scrollTop = 0;
Upvotes: 0
Reputation: 704
Did you try scrollIntoView
?
Here's some docs: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
Upvotes: 1
Reputation: 89
Many many hours went into creating this fix, I could not find a solution that worked online so I want to share it here to save future people my pain.
You can change the button that opens your modal from a button/div element to be an <a></a>
anchor element. Set the anchors href to be the top of the content in the modal. Then go find your file that contains the top content of your modals and give it an id equal to the href.
In my case, my button was an <a href="top-modal">
, and then I found the top heading for the content in my modal and gave it id="top-modal"
. This makes it so whenever you click the button that opens your modal, it will scroll to the top of that modal.
Upvotes: 0