简体   繁体   中英

How to scroll to the top of a modal

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.

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.

Did you try scrollIntoView ?

Here's some docs: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM