Search code examples
javascripthtmlcsssimplemodal

How to make div modal scrolled to the top each time I open it?


I have built a modal by pure html, CSS, javascript. It would pop-up as I click a button on the main page.

However, if I scroll down the model and close it, it would show the scrolled-down view as I reopen it. How can I make it always show the content at the top each time I open the model?

Here is my code:

<div class="button" id="btn"></div>

<div class="modal" id="mymdl">
    <div class="modal-content" id="mdl-con">
        <div class="modalwidth">
            <img class="image-title" id="img-ttl" src="./img/banner.png">
            <span class="close" aria-hidden="true">&times;</span>
        </div>
        <div class="paragraph">
            Here is the main content.
        </div>
    </div>
</div>
document.getElementById('btn').addEventListener('click', function(e) {
    modal.style.display = "block";
});

var closeX = document.getElementsByClassName("close")[0];
closeX.onclick = function() {
    modal.style.display = "none";
}

I have tried window.scroll method provided in the solution of this problem, but it didn't solve my problem.

I'm new to html, css, and javascript. Any idea would be appreciated! Thanks in advance.


Solution

  • You can use element.scrollTop = 0 to scroll it to the top.

    For example if .paragraph is what's getting scrolled, you can use something like this:

    const modal = document.getElementById("mymdl");
    
    document.getElementById('btn').addEventListener('click', function(e) {
        modal.style.display = "block";
    });
    
    var closeX = document.getElementsByClassName("close")[0];
    closeX.onclick = function() {
        modal.querySelector(".paragraph").scrollTop = 0; //scroll to the top
        modal.style.display = "none";
    }
    .modal
    {
      position: fixed;
    }
    
    .modal-content
    {
      border: 1px solid black;
    }
    
    .paragraph
    {
      overflow: auto;
      height: 50vh;
      white-space: pre;
      text-align: center
    }
    
    .paragraph > div
    {
      height: 120%;
    }
    
    .paragraph > span
    {
      position: relative;
      bottom: 0;
    }
    
    .button,
    .close
    {
      cursor: pointer;
    }
    <div class="button" id="btn">open modal</div>
    
    <div class="modal" id="mymdl">
        <div class="modal-content" id="mdl-con">
            <div class="modalwidth">
                <img class="image-title" id="img-ttl" src="./img/banner.png">
                <span class="close" aria-hidden="true">&times;</span>
            </div>
            <div class="paragraph">
            <div>Here is the main content.
    scroll down</div><span>bottom</span>
            </div>
        </div>
    </div>