Monday, June 3, 2013

jQuery Modal Dialog & Scrolling

Recently I was loading some documents into a jQuery modal dialog. Everything was going well until I added content to the dialog and all of a sudden, when running the page and opening the dialog, it would scroll to the bottom of the document. Not sure what causes this but someone suggested it may be caused due to a link.

Now to fix that annoying behavior...

The element clicked to cause the dialog to open:
<div id=tabs">
   <a href="#" class="modal">The Modal</a>
</div>
We have a div that contains the contents of the modal:
<div id="modalContent">
   // content here
</div>

At the top of that div, sneak in another div that contains a link, this is going to be the target that is set in the modal dialog:
<div id="modalContent">
   <div id="topPosition">
      <a href="#" class="ui-dialog-relative">&nbsp;</a>
   </div>
   // other modal content
</div>

The jQuery:
$('a.modal').click(function (e) {
   e.preventDefault();
   $('#modalContent').dialog({
      modal: true,
      autoOpen: false,
      width: 1100,
      buttons: {
         Print: function () {
            window.print();
         },
         Close: function () {
            $(this).dialog("close");
         }
      },
      open: function () {
         $('.ui-dialog-relative :link').blur();
         $('#topPosition').focus();
      },
      focus: function (event, ui) {
         $('#topPosition').focus();
      }
   });

   $('#modalContent').dialog('open');
});

The key is to hook into the ui-dialog-relative href and give that the focus when the dialog opens. Calling blur ensures that the link itself is not visible.

This did solve the initial problem, however going back to this a few days later I removed the open and focus functions from the dialog settings and things worked. Strange but initially it did solve the problem.