I previously showed the basic usage of the jQuery UI dialog. In this article, I’ll show how to open a page in a dialog. We’ve all been to sites where there’s a help link that opens a popup with some short help text. This is usually done with a simple window.open
call attached to the click event of the link.
what is this?
Making it better
The one thing that this code has going for it is that users without JavaScript will still be able to get to the page with the help content. Of course, a better implementation would move the JavaScript out of the HTML, properly separating content from behavior. We can spruce this up by loading the content into a dialog instead of a new window:
$(document).ready(function() { $('#page-help').each(function() { var $link = $(this); var $dialog = $('') .load($link.attr('href')) .dialog({ autoOpen: false, title: $link.attr('title'), width: 500, height: 300 }); $link.click(function() { $dialog.dialog('open'); return false; }); }); });
How it works
We’re finding the link, loading the contents of the linked page into a div and creating a dialog from that div. We then bind a click event to the link to show the dialog. This code by itself will work in many situations. However, the page you’re linking to may have a heading that you’re already reproducing with the dialog title. There may also be other elements on the page that won’t make sense in a popup, such as navigational elements or a page footer. Luckily the .load()
function allows us to pass in a selector to find the contents that we care about. In this example we’ll assume the main content of the page is in a div with an id of content.
$(document).ready(function() { $('#page-help').each(function() { var $link = $(this); var $dialog = $('') .load($link.attr('href') + ' #content') .dialog({ autoOpen: false, title: $link.attr('title'), width: 500, height: 300 }); $link.click(function() { $dialog.dialog('open'); return false; }); }); });