Prevent Page behind JQuery UI Dialog from Scrolling

I love jQuery UI dialogs. I hate when scrolling the dialogs’ content to the bottom starts scrolling the page underneath, moving the dialog off screen. With some smart structure of the page’s html, that can be avoided.

jquery-UI-dialogFirst, let’s show the problem. This is a basic page with a jQuery UI dialog shown. The dialog is modal, so it prevents access to the page behind. There are scroll bars on both the dialog and then page. Scrolling the dialog’s content with the mouse wheel works fine, until the bottom of the dialog is reached. At this point, I do expect continued rolling of the wheel to hit a dead end. Unfortunately it doesn’t. It starts scrolling the page behind the dialog instead. Rolling some more will eventually move the dialog off page, leaving the user with a large disabled area. That is definitely not a good user experience. Here is a small live demo.

The Body Scrolls

jquery-UI-scroll-badThe problem appears because the jQuery UI dialog is just a cleverly designed div that is added dynamically to the end of the body. Pressing F12 on the live demo page shows that there is a <div> right before the closing </body> tag. That div is the jQuery UI dialog.

When hitting the bottom of the dialog it can no longer be scrolled. Instead the parent element – the entire <body> is scrolled and the dialog moves off page. The solution is to no longer make the <body> scrollable but instead move the scrolling to a separate <div>.

jQuery UI Replacement for alert()

The Javascript alert(message) is a simple one-liner to show a message on a web page. It uses a standard system dialog box to display the message. On a site where most other UI elements are built using jQuery UI it is more natural to display the alerts in the same style. Unfortunately there is no built in one-liner for displaying a simple alert in jQuery UI, but it is easy to add an own one.

This is a standard jQuery UI dialog displayed using one line of code. It follows the same theme as the rest of the jQuery UI widgets used on the site and it behaves like a normal modal dialog. The code used for displaying the dialog is $.alert("message", "title"), which is a jQuery extension I added with a few lines of code.

Software Development is a Job – Coding is a Passion

I'm Anders Abel, an independent systems architect and developer in Stockholm, Sweden.

profile for Anders Abel at Stack Overflow, Q&A for professional and enthusiast programmers

Code for most posts is available on my GitHub account.

Popular Posts



Powered by WordPress with the Passion for Coding theme.