简体   繁体   中英

How can I make sure the jQuery loaded scrollable modal content always scrolls back to the top?

I have a Boostrap modal jQuery function that I use to call dynamic content through AJAX. The modal is also scrollable and has a fixed height, so it's possible that someone scrolls down inside the modal and then closes it (through a button at the bottom).

The issue now is that when another modal is opened, it opens at the same location where the previous modal was closed, meaning possibly at the bottom, which is confusing to the user.

Is there a simple way to make the modal always open (focus?) at the top of the content? Here is my function:

function open_box(params)
  {                 
    dump(params);
      var URL=ajax_url+"/?"+params;

        var modal = $('#modal');
        modal
            .find('.modal-body')
            .load(URL, function (responseText, textStatus) {
                if ( textStatus === 'success' || 
                     textStatus === 'notmodified') 
                {
                    modal.modal("show");
                }
        });  
}

The CSS is:

    .modal-content {
        overflow: auto;
    }

    .modal-dialog {
    width: calc(100% - 100px);
    margin: 100px auto;
    height: 85%;
    max-height: calc(100% - 100px);
    max-width: 550px;
}

I tried adding .scrollTop(0) to the code (right below find ) and that didn't work.

Try to use native browser method of HTML elements scrollIntoView() ( Docs ). If you know element that is exactly the top element in the loaded HTML, you can try to call element.scrollIntoView() after your popup is shown. or you can determine a first child of a loaded content and scroll it to top. Something like this:

function open_box(params)
  {                 
    dump(params);
      var URL=ajax_url+"/?"+params;

        var modal = $('#modal');
        var modalBody = modal.find('.modal-body');
        modalBody
            .load(URL, function (responseText, textStatus) {
                if ( textStatus === 'success' || 
                     textStatus === 'notmodified') 
                {
                    modal.modal("show");
                    modalBody.get(0).children[0].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