Dmitry Gorshkov
Dmitry Gorshkov

Reputation: 4070

How to reset scroll position of modal in bootstrap3?

I have a bootstrap v3 modal, like in the documentation.

When I open the modal for a first time ('Launch demo model' button) a vertical scroll bar is in a top position. If I scroll down and click 'Cancel' in modal it will close. It is ok. But if I open modal again it will be already scrolled down. And this is case which I would like to avoid. What should I do to open modal in a top position?

Upvotes: 6

Views: 13912

Answers (5)

LostNomad311
LostNomad311

Reputation: 2065

Here's how I got this functionality working . First set up the shown event of the modal .

$(document).ready(function () {
    var modalMatrix = $('#modalMatrix');
    modalMatrix.on('shown.bs.modal', function () {
        modalMatrix.find('.modal-body').scrollTop(0); // This is important , for me the scrollbar is in the body of the modal .
    });
});

Then I show the modal , as usual .

$('#modalMatrix').modal('show');

Upvotes: 1

King Friday
King Friday

Reputation: 26086

working in production

$('#my-modal').on('shown.bs.modal', function () {
    $('#my-modal').scrollTop(0);
});

Upvotes: 5

someok
someok

Reputation: 111

Bootstrap 3 modal

$modal.off('shown.bs.modal').on('shown.bs.modal', function() {
    if ($modal.scrollTop() > 0) {
        $modal.scrollTop(0)
    }
}

Upvotes: 0

Dmitry Gorshkov
Dmitry Gorshkov

Reputation: 4070

I have resolved it by setting a focus on the top input element om my modal:

    $("#RuleDialog").on('shown.bs.modal', function() {
        $('#LinkedRuleName').focus();
    });

Upvotes: 0

finnmich
finnmich

Reputation: 121

I think you would need to to use the events that fire when the modal is opened to reset the scrolling.

Something like:

$('#myModal').on('shown.bs.modal', function () {
  window.scrollTo(0,0);
});

Depending on your page you might wantto use some jQuery or animations:

$('#myModal').on('shown.bs.modal', function () {
 $('html, body').animate({
   scrollTop: $("#myModal").offset().top
 }, 1000);
});

Upvotes: 1

Related Questions