Howto: Use jQuery UI dialog as reusable modal prompt

jQuery UI has always been my favorite tool for creating custom and rich User Interface. On my last project, I thought of using the UI dialog as reusable modal prompts, just like some jQuery plugins like Colorbox, Fancybox etc. But while doing that I faced some problem like, chaining the dialog to multiple class based selectors and attaching the dialog open events to respective anchor elements. After reading the documentation a bit, I came up with a nice solution which works and does not load the browser! So, in this post I am going to discuss it. But before we do, as usual, here are the links to the online demo and the script!

Demo[download id=”11″ format=”1″]

#1: The problem & the approach:

  • The UI dialog box automatically opens when the document(page) loads, and gets destroyed when the close button is clicked.
  • We want to make several UI dialogs using the css class selector and also want to attach their opening call to respective anchor elements. Doing the thing with specific ID selector is not a good idea because we have to write separate code for each of the dialog and the firing anchor elements.
  • If we attach the dialog UI directly to the anchor element, then it will get destroyed after first use and the anchor will not bring any further dialog prompt. So we need to save the dialog under some sort of variable and must attach that dialog’s open call to the click even of the anchor using that variable.
  • So we can actually loop through all the anchor elements (they should be given same class names for easy looping) and somehow get their corresponding dialog prompts saved inside somehow related tags and save those dialogs inside some local variable.

#2: The structure of the CODE:

Considering all these problems and their resolving approaches, we first make the XHTML code as follows:

<a class="dialog_but" href="#">Button 1</a> 
<div class="dialog_content">This is Dialog One!</div>

<a class="dialog_but" href="#">Button 2</a> 
<div class="dialog_content">This is Dialog One!</div>

<a class="dialog_but" href="#">
    Button 3
</a>
<div class="dialog_content">
    <p>Another dialog prompt with a little bit <em>More</em> <strong>HTML</strong></p>
    <img src="image/nice_robot.png" style="float: right; margin: 0 0 10px 10px" />
    <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi et mauris erat. Morbi placerat semper sodales. Pellentesque sollicitudin quam id erat iaculis convallis eleifend odio aliquet. Aenean pulvinar adipiscing enim id sodales. Pellentesque tellus eros, interdum vel dignissim ac, dignissim sit amet dui. Integer felis augue, condimentum eget ullamcorper et, hendrerit at lacus. Nulla placerat ipsum at risus consectetur sit amet suscipit dui pellentesque. Sed sed elit a orci ornare posuere bibendum sodales turpis. Fusce euismod ante ut nunc pharetra facilisis. Nulla laoreet malesuada lacus, in sagittis urna adipiscing nec. Proin accumsan dolor vitae urna convallis non pretium odio convallis. Integer nisi lorem, varius in bibendum sit amet, scelerisque vel libero. Proin placerat pharetra congue. Sed tempus augue vitae nisl viverra hendrerit at nec purus. Vivamus laoreet erat vel turpis scelerisque at elementum sapien ultrices. Nulla at leo diam. Praesent hendrerit imperdiet ultricies. Curabitur vestibulum turpis in lacus faucibus convallis. Quisque nec magna nulla. 
    </p>
    <p>
        Nullam orci nisi, laoreet eget adipiscing sit amet, porta ut leo. Nulla at condimentum mauris. Duis sed lectus ligula, a scelerisque eros. Donec bibendum eleifend ullamcorper. Pellentesque eu ante sed augue feugiat condimentum sit amet eu leo. Sed sodales ipsum at risus iaculis ac bibendum odio faucibus. Phasellus leo ligula, euismod id interdum vel, convallis ac sapien. Sed ut felis mauris. Suspendisse faucibus aliquam tortor a convallis. Fusce aliquet libero id arcu condimentum tincidunt. Morbi laoreet, ante nec tristique porta, eros odio molestie urna, eget accumsan nibh ligula ut nisi. Curabitur suscipit eros at sapien vestibulum blandit ut vitae orci. Integer vitae risus ante, in dapibus felis. Curabitur dignissim nisl ut dui suscipit at eleifend metus feugiat. Maecenas porta sagittis aliquam. 
    </p>
</div>

As you might already have noticed, the a.dialog_but elements are the dialog firing elements, and the div.dialog_content elements next to them are the div’s actually holding the dialog prompt data! Keeping this structure in mind, we code the following jQuery code!

//do when the dom is ready
jQuery(document).ready(function($) {
    //loop through every button anchor element
    $('.dialog_but').each(function() {
        //create a local scope of a dialog variable to attach
        var $dialog;

        //create the dialog for the div.dialog_content standing next to the anchor element
        //we make the autoOpen false so that it can be reusable
        //also we set the modal = true to appear the dialog as a modal prompt
        $dialog = $(this).next('div.dialog_content').dialog({modal: true, autoOpen: false, width: 600});

        //now attach the open even of the dialog to the anchor element
        $(this).click(function(e) {
            //prevent the anchor element to go to the hyperlinked page
            e.preventDefault();

            //open the dialog
            $dialog.dialog('open');
        });
    });
});

As obvious, the code will work something like

  1. When the document is ready, loop through every a.dialog_but elements (using the jQuery .each API).
  2. Inside the .each function, create a local variable $dialog (using the keyword var) and store the dialog inside that variable.
  3. The dialog element is nothing but the div.dialog_content next to it (using the jQuery .next API).
  4. Also, at the same time, we add a click event to that anchor. The event is nothing but firing the open call of the $dialog

In this way we create a simple and working modal dialog prompt using jQuery UI.

A complete will be something like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <!-- include the jQuery and jQuery UI JS and CSS code -->
        <link rel="stylesheet" type="text/css" href="http://jquery-ui.googlecode.com/svn/trunk/themes/base/jquery.ui.all.css" />
        <script src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js' type='text/javascript'></script>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.min.js"></script>

        <!-- The jQuery code for the UI dialog -->
        <script type="text/javascript">
            //do when the dom is ready
            jQuery(document).ready(function($) {
                //loop through every button anchor element
                $('.dialog_but').each(function() {
                    //create a local scope of a dialog variable to attach
                    var $dialog;

                    //create the dialog for the div.dialog_content standing next to the anchor element
                    //we make the autoOpen false so that it can be reusable
                    //also we set the modal = true to appear the dialog as a modal prompt
                    $dialog = $(this).next('div.dialog_content').dialog({modal: true, autoOpen: false, width: 600});

                    //now attach the open even of the dialog to the anchor element
                    $(this).click(function(e) {
                        //prevent the anchor element to go to the hyperlinked page
                        e.preventDefault();

                        //open the dialog
                        $dialog.dialog('open');
                    });
                });
            });
        </script>
    </head>
    <body>
        <div>
            <p>
                <a class="dialog_but" href="#">Button 1</a> <div class="dialog_content">This is Dialog One!</div>
            </p>
            <p>
                <a class="dialog_but" href="#">Button 2</a> <div class="dialog_content">This is Dialog One!</div>
            </p>
            <p>
                <a class="dialog_but" href="#">
                    Button BIG
                </a>
                <div class="dialog_content">
                    <p>Another dialog prompt with a little bit <em>More</em> <strong>HTML</strong></p>
                    <img src="image/nice_robot.png" style="float: right; margin: 0 0 10px 10px" />
                    <p>
                        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi et mauris erat. Morbi placerat semper sodales. Pellentesque sollicitudin quam id erat iaculis convallis eleifend odio aliquet. Aenean pulvinar adipiscing enim id sodales. Pellentesque tellus eros, interdum vel dignissim ac, dignissim sit amet dui. Integer felis augue, condimentum eget ullamcorper et, hendrerit at lacus. Nulla placerat ipsum at risus consectetur sit amet suscipit dui pellentesque. Sed sed elit a orci ornare posuere bibendum sodales turpis. Fusce euismod ante ut nunc pharetra facilisis. Nulla laoreet malesuada lacus, in sagittis urna adipiscing nec. Proin accumsan dolor vitae urna convallis non pretium odio convallis. Integer nisi lorem, varius in bibendum sit amet, scelerisque vel libero. Proin placerat pharetra congue. Sed tempus augue vitae nisl viverra hendrerit at nec purus. Vivamus laoreet erat vel turpis scelerisque at elementum sapien ultrices. Nulla at leo diam. Praesent hendrerit imperdiet ultricies. Curabitur vestibulum turpis in lacus faucibus convallis. Quisque nec magna nulla. 
                    </p>
                    <p>
                        Nullam orci nisi, laoreet eget adipiscing sit amet, porta ut leo. Nulla at condimentum mauris. Duis sed lectus ligula, a scelerisque eros. Donec bibendum eleifend ullamcorper. Pellentesque eu ante sed augue feugiat condimentum sit amet eu leo. Sed sodales ipsum at risus iaculis ac bibendum odio faucibus. Phasellus leo ligula, euismod id interdum vel, convallis ac sapien. Sed ut felis mauris. Suspendisse faucibus aliquam tortor a convallis. Fusce aliquet libero id arcu condimentum tincidunt. Morbi laoreet, ante nec tristique porta, eros odio molestie urna, eget accumsan nibh ligula ut nisi. Curabitur suscipit eros at sapien vestibulum blandit ut vitae orci. Integer vitae risus ante, in dapibus felis. Curabitur dignissim nisl ut dui suscipit at eleifend metus feugiat. Maecenas porta sagittis aliquam. 
                    </p>
                </div>
            </p>
        </div>
    </body>
</html>
Demo[download id=”11″ format=”1″]

For more information, you may like reading about jQuery UI dialog documentation or download the source code from above and try it yourself!

If you have any trouble understanding then feel free to ask! Also don’t forget to give your valuable comments.