The jQuery UI – Part 1 The Dialog

Posted by mdrisser on 2008/05/16 under Development, JavaScript, UI, Uncategorized, jQuery | 30 Comments to Read

OK, I admit it, I love the jQuery Framework, its fast, easy to use, extensible and very well documented. The only thing that is currently lacking in documentation is the new UI (User Interface). Since that is the case, and I see a lot of potential in the new UI, I’ve decided to write a series of tutorials covering the UI. Let me just say right now, I’m not jQuery expert, nor am I an expert on the UI.

As of the time of this writing, the current version of the UI is 1.5b4, so things may change, if they do I’ll come back and update these tutorials as necessary.

I suppose that the best starting point is with downloading and setting up the UI Library. You can download the UI from the jQuery UI Site. After you’ve downloaded it unzip it into a directory on your web server (I’ll be using ’scripts/jquery’, but feel free to use your own directory structure). The download also contains a beta version of the core jQuery library, with removes the dependancy on the Dimensions plugin, so we’ll be using that version.

We’ll start off with the UI Dialog, as I think that may be one of the most used pieces of the library. The Dialog shares a single required dependency and has two optional ones (the current documentation calls the required one ui.base.js, but in 1.5b4 its actually ui.core.js) and the two optional ones are resizable and draggable. We’ll slowly build this up so for now we’ll just include jQuery, Dimensions, the one required dependency and then the dialog component.

At this point your HTML should look something like this:


    
        
        
        
    
    
    

Now we need to add a container to act as the dialog. This can be any valid HTML element, but we’ll use a div with an id of ‘dialogTest’. We also need to tell jQuery that our div is going to be a dialog.


    
        
        
        
        
    
    
Hey, check it out!I'm a dialog box!!!

Notice that we’ve included a title attribute to our div, the text of this attribute will be seen in the title bar of the dialog. Why don’t you go ahead and give it a try?

If you’ve tried the code that we’ve been working on so far, you’ve seen that its not very inspiring. We could just go ahead and create some CSS to make it look better, or we can use the UI themes (well OK, there’s only one theme right now, but I’m working on another one for the UI).

If you remember when you unzipped the UI source, there was a themes folder in there, this folder contains all the CSS and images we need to make our dialog look better. So let’s go ahead and add that in.

The one theme that is in there, ‘flora’, has several CSS files in its directory, along with a bunch of images. If you take a look at the CSS filenames you’ll see that there is one for each component, one for all components, and one other one. Now we can theme our dialog in one of two ways, we can use the flora.all.css file, or we can pick and choose just the CSS files that we need. The choice is up to you, but this is a simple example and we don’t need all the extra stuff, so we’ll pick and choose.

Add the CSS file flora.dialog.css to the head of your page. We also need to add the ‘flora’ class to our div, we could just add the class attribute to the div itsself, but hey, this is jQuery, we’ll do it dynamically.

Your code should now look like this:


    

        
        
        
        
    
    
Hey, check it out!I'm a dialog box!!!

Go ahead a test it. It looks much better now doesn’t it?

Remember those two optional dependencies I mentioned earlier? Let’s go ahead and add one of them to our dialog. We’ll add Resizable to our dialog, which may or may not be very useful for our humble little dialog, but it does help demonstrate the flexibility of the jQuery UI.

So go ahead and add the file ui.resizable.js to your page and test it out.

Something appears to be wrong with our little dialog, almost like we somehow broke something. But fear not, there is an easy fix, if you haven’t figured it out already. We’ll turn back to our Flora theme for the answer and include one more CSS file, flora.resizable.css. Now if you try it looks much much better.

If your not following along on your own, here’s a shot of what we’re looking at:
The jQuery UI Dialog in Action

So how do we get our dialog to only show up when we want it to? That’s actually pretty simple, dialog takes several options, the one we’re most interested in right now is ‘autoOpen’. ‘autoOpen’ takes a boolean argument to determine whether or not it should open automatically. I know, I know, the name gave it away. By default, ‘autoOpen’ is set to true, but we want to set it to false, so it will only open when we say so.

We also need to decide when to show the dialog. Since this is a simple demonstration, we’ll just add a button to the page that, when clicked, shows the dialog.

And now for the how. It turns out to be remarkably easy as well. If a dialog is not visible and we pass it ‘open’ as an argument, it will be displayed. take a look at the code below to see how we’ll accomplish this.


    

        
        
        
        
    
    
        
Hey, check it out!I'm a dialog box!!!

Now when you click on the button, our dialog will appear.

The dialog takes several other options as well, including width and height, modal or not, etc. Take a look at the docs here, and play around with it.

  • Share/Bookmark
  • rdworth said,

    This is great. jQuery UI will surely benefit from it. I look forward to more articles.

  • bmckenzie said,

    Hi,

    Do you know of a working demo of a modal ui.dialog . I’m thinking about replacing thickbox — but I can’t seem to make a the modal window with UI 1.5b2.

    Thx

  • vvvlad said,

    I’m new to jQuery, and I think you are doing a great job.
    Please continue posting tutorials – they are really helpful!

    Thank you

  • mdrisser said,

    I apologize for not having gotten back to anyone sooner, I’ve been trying to wrap-up a big project at work and its taken a lot of my time, but we’re just about done now, so things will be almost back to normal.

    @rdworth, @vvvlad: Thank you for your kind words.

    @bmckenzie: Try upgrading to 1.5b4 and using the supplied jquery library, then in your constructor for the dialog set modal: true, so that it looks something like:
    $(’#dialogTest’).dialog({modal: true});

  • Riyad said,

    Hi, I have faced problem with modal dialog. i set the modal true.than set overlay options.the code looks like:it says a javascript error.
    $(’#popUpNote’).dialog({
    title: ‘Add Note’,
    buttons: {
    ‘Save’: function() { $(this).dialog(’close’); ajaxSaveNote(); },
    ‘Cancel’: function() { $(this).dialog(’close’); }
    },
    autoOpen: false,
    position: [150,200],
    modal: true,
    overlay:{color:’#000′}

    });

  • mdrisser said,

    @Riyad Could you provide a little more information? What version of the UI? What version of jQuery? What is that exact error message that you are seeing?

    If you can provide that information, I will do what I can to help you solve your problem.

  • vvvlad said,

    Hi,
    I have a simple question.
    Using almost exact copy of your code:

    $(document).ready(function() {
    // Tell jQuery that our div is to be a dialog
    $(’#dialogTest’).addClass(’flora’).dialog();

    $(’#bttn1′).click(function() {
    $(’#dialogTest’).dialog(’open’);
    });
    });

    Open the Dialog
    Hey, check it out!I’m a dialog box!!!

    Why the dialog is not draggable?
    Another question:
    Why when I include jquery.ui-all-1.5b4.js and remove all the others except jquery.js the dialog doesn’t work?

    Thank you

  • vvvlad said,

    for some reason all html code was striped in previous comment, so I include this:

    jquery-1.2.6.min.js
    ui.core.js
    ui.dialog.js
    ui.draggable.js
    ui.resizable.js

  • vvvlad said,

    @Riyad:
    I couldn’t use the modal part:
    {
    modal: true,
    overlay:{color:’#000′}
    i think because ui.draggable doesn’t work, but except that just use ” instead of ‘ everywhere and it works :)

  • mickbw said,

    Hi,

    It seems the real power of this ui.dialog would be in the replacement of the javascript alert() with a skinnable dialog box.

    I’ve looked for examples to do this and use the ui.dialog as a confirm and haven’t found any. Could you direct me to a place where a newbie could find such information?

  • mdrisser said,

    @vvvlad: Did you remember to include the CSS files for draggable?

    @mickbw: You can emulate the confirm dialog behavior by setting the buttons option:
    $(’#dialogDiv’).dialog(buttons: {(’Ok’, callback_for_ok_click()),’Cancel’, callback_for_cancel_click())});
    More information on this is available in the docs:
    http://docs.jquery.com/UI/Dialog/dialog#options

  • Copyright said,

    Thank you for this nice tutorial, I’m new in jQuery and I had some problems with UI Dialog, fortunately, I found your tutorial, you make it very simple.
    Again, thanks a lot.

  • Jerome Mrozak said,

    In response to Riyad, I have no problem with the popUpNote code. It works fine for me —- as long as you mind the apostrophes. Your code has a mix of left-apostrophes and right-apostrophes, as though it were created in Microsoft Word. You really need the apostrophe from a plain text editor. Do a search-and-destroy on that code and you’ll be ok.

  • Jerome Mrozak said,

    I have another problem, perhaps with the most current version of the dialog library. Here are my parameters:

    * I’m using MSIE 7 (what I have installed, don’t now about MSIE 6)
    * I have the ui.draggable.js installed in the web page
    * My sample web page is so long that it scrolls off the top of the screen. That is, my “open the dialog” button is at the bottom of a long page.
    * After I open the dialog, it displays OK near the bottom of the page. It is where it belongs.
    * If I click on the “title bar” (the region occupied by the “Add Note” text), and then begin to drag the dialog, the dialog disappears!
    * Actually, it repositions itself near the very top of the web page.
    * If I go up there to drag it again, the dragging goes OK.
    * The code has no such problems with Firefox.

    Is there a bug report, or fix, for this yet?

  • ikoto said,

    Hi,

    When the dialog box shown, I want that it sizes itself to its content, how can i do this ?

    thanks,

  • jerome said,

    Thanks so much for this step by step, show all html approach. :)

  • Tomas said,

    Hi,
    I’m trying to use dialog with load. Like this

    $(’.test’).click(function() {
    $.get(”get.php”, function(data){
    $(”#result”).load(’test.php?data=’ +data, function() {
    $(”#result”).dialog({
    resizable: false,
    modal: true,
    buttons: {
    “Close”: function() { $(this).dialog(”close”); }
    }
    });
    });
    });
    });

    Everything works fine first time i klick my link. Next time everything except the dialog works. Load and get fires off like it is supposed to, but no dialog.

    Any ideas?

    I downloaded fresh copy’s of Jquery and UI yesterday.
    Firebug dosent show any errors, just shows that get and

  • Juggernt said,

    Tomas- You probably figured the problem out long ago, but since I experienced it myself (and its probably pretty common):
    THE (likely) ANSWER: The first time you OPEN/initialize the dialog you must pass in the options (like you did). However, once initialized, you must call the ‘open’ method $(this).dialog(”open”); in order for subsequent clicks to work and re-produce the dialog.
    -Jay

  • Lesliê Cardoso said,

    Fine! I’m with problem. When I click button close,

    var $jform = jQuery.noConflict();

    Adicionar endereço

    with code $jform(’#div_endereco’).dialog(’open’)
    I initialize the dialog, but my height this is auto after. Someone help! Thanks’

  • Lesliê Cardoso said,

    sorry! The code again!

    $jform(’#div_endereco’).dialog({
    bgiframe: true,
    height: 180,
    width: 620,
    modal: true,
    overlay: {
    backgroundColor: ‘#000′,
    opacity: 0.75
    },
    title: ‘Adicionar endereço’,
    buttons: {
    ‘Salvar’: function() {
    if(FormVal(document.getElementById(’formulario_endereco’)))
    document.getElementById(’formulario_endereco’).submit();
    },
    ‘Cancelar’: function() { $jform(this).dialog(’close’); }
    }
    });$jform(’#div_endereco’).dialog(’open’);

    with code $jform(’#div_endereco’).dialog(’open’)
    I initialize the dialog, but my height this is auto after. Someone help! Thanks’

  • Nelson said,

    Hi. I am new to JQuery and trying to use the UI. Thank you for providing such a tutorial.

    I am following the quide, but I am getting an error of “Invalid Argument” on line 1121. My code is less than 20 lines. So, I think one of the jquery js file may not be compatible? I Am I using a wrong version?

    I downloaded the latest zip jquery.ui-1.5.3 and inside I have jquery-1.2.6.js
    and in the ui folder there is the
    ui.core.js, ui.dialog.js.

    My code looks like this:



    $(document).ready(function() {
    // Tell jQuery that our div is to be a dialog
    $(’#dialogTest’).dialog();
    });

    Hey, check it out!I’m a dialog box!!!

    Your response is higly appreciated.

    Thanks.

  • mdrisser said,

    @Nelson I haven’t had the chance to check out the latest release of jQuery UI, I’ll take a look at it tonight and see what I can find for you.

  • Dimitar Ivanov said,

    Hi guys,

    I have a table with many rows, each row has a ‘delete’ link with ‘rev’ attribute contains the ID of the record.
    // Links
    delete
    delete
    delete

    // Initialize the dialog
    $(document).ready(function() {

    $(”#dialog”).dialog({
    autoOpen: false,
    bgiframe: true,
    resizable: false,
    draggable: false,
    height:140,
    modal: true,
    overlay: {
    backgroundColor: ‘#909090′,
    opacity: 0.5
    },
    buttons: {
    ‘Delete’: function() {
    $(this).dialog(’close’);
    delFunc(’http://www.domain.com/delete’,$(this).attr(’rev’)); //Here is my problem (I don’t know how to get second param for ‘delFunc’
    },
    ‘Cancel’: function() {
    $(this).dialog(’close’);
    }
    }
    });
    });

    // bind ‘click’ event to the anchor links

    $(’a.delete’).click(function(){
    $(’#dialog’).dialog(’open’);
    return false;
    });

    //
    delFunc is Ajax function who expect the value from ‘rev’ attribute. So is there a way to pass some custom params to the .dialog method?

    Cheers,

  • JohnM said,

    Thank you, I’m a jQuery newbie and the tutorial helps me understand the jQuery world.
    It works great.
    Thanks again.

  • faisal said,

    thanks you. it is very useful for me,

  • IE user said,

    wow, this page is rife with javascript errors

  • cnsk said,

    Great Tutorial. Thanks

  • Brustwarzenpiercing said,

    Nice Tutorial. But i have one question. I want to add the dialog a img. can anybody give me an example please?

  • Steve Brown said,

    I want to have a dialog with ‘fixed’ position, so it doesn’t scroll when the user scrolls the window (yes, I know this won’t work in older IEs).

    If I make the div I create the dialog from fixed, then the contents, but not the frame, of the dialog stay put on scrolling.

    Any ideas? (it’s probably obvious: sorry!)

  • chepe263 said,

    A good idea is open the example of jquery ui and copy the code of the scripts location and the css to avoid problems

Add A Comment