Creating a Dialog with jQuery UI (2)

Yesterday I blogged about my experience working with jQuery UI and the Dialog widget. In general it went well (after a slightly rough start), but I was able to get things working nicely and even played around with the themes a bit. I thought things were working fine. I could click my link, and the dialog would show up. (See the exciting, thrilling demo here.) However, there was a bug with how I used the code. If you click on the link it will load the dialog, but if you close it, you can't reopen it. Here is how I fixed the problem. First, let's take a quick look at how the dialog was set up:

<script> function showDialog(){ $("#example").dialog(); return false; } </script>

The function showDialog was tied to a simple link on the page. Clicking it once works fine, but any subsequent link would do nothing. Checking the docs a bit closer, I discovered that the .dialog() call was mostly meant to be used to setup the Dialog, not show it. It certainly will show a dialog of course, as you can see in the demo, but really it should only have been used once. Here is a modified version that works nicer:

<script> function showDialog(){ $("#example").dialog("open"); return false; }

$(document).ready(function() { $("#example").dialog({autoOpen:false}); });


In this version, I use the $(document).ready to set up the dialog box when the page loads. Notice the use of autoOpen:false. This will set up my dialog but not show it. Now my showDialog function can run dialog("open") to pop open the dialog no matter how many times it is closed.

You can see a demo of this, and the amazing 'Swanky Purse' theme, here: Remember you can View Source for the complete page.

I will also point out two other fixes by posters on the last blog entry. One by Akira and one by Joel Cox.

Like This?

If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can also subscribe to the email feed to get notified of new posts.