Jquery – How to keep scroll position in SimpleModal dialog

dialogjquerymodal-dialogscrollsimplemodal

How is it possible to keep the scroll position of a scrollable div within a modal dialog when it is re-opened?

I modified the basic downloadable example of simplemodal as follows:

<div id="basic-modal-content">
    <h3>Scrollable Modal Dialog</h3>
    <div style="width: 150px; height:100px; overflow: auto;">
        a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>
    </div>
</div>

Best Answer

I tested this solution with Simple Modal and it works

If you are using there Basic Dialog demo, just change out the basic.js file for this code. It just gets the scrollTop before the dialog closes, and resets it when the dialog reopens. We have to call the full selector for the div each time because of how SimpleModal works:

$(document).ready(function () {
  var scrollTop = null;
  $('#basic-modal input.basic, #basic-modal a.basic').click(function (e) {
    e.preventDefault();
    $('#basic-modal-content').modal({
      onShow: function(){
        if(scrollTop !== null) $('#basic-modal-content > div').scrollTop(scrollTop);
      },
      onClose: function(){
        scrollTop = $('#basic-modal-content > div').scrollTop();
        $.modal.close();
      }
    });
  });
});