Monday, June 25, 2012

Cleanly replace links with jQuery UI Dialogs.

This but of code along with a bit of link decoration will automatically open all specified links in dialog popup windows instead of in new browser windows.  It benefit here is that this code is quite small, clean, and automatically applied to all matched elements on the page without having to write custom code or hooks for each link.

First of all make sure that you are including jQuery, jQuery UI and a jQuery UI Stylesheet.

<script src=""></script>
<script src=""></script>
<link href="" rel="stylesheet"></link>

Next add the following code to a external javascript file that is included on this page or into the page code itself. Not that this needs to be included/executed after the above scripts are included.

// make sure the page is fully loaded.
$(document).ready(function() {
  // For each link makred up with the popup attribute change the link to open the contents in a jquery dialog instead.
  $("a[popup]").each(function() {
    $(this).click(function() {
      dest = $(this).attr("popup");
      // Get the page contents with a background ajax query.
      $.get($(this).attr("href"), function(data) {
        // Push the results into a div tag with a custom id to spit out the script and style elements.
        $("<div id='"+dest+"' class='"+dest+"'>" + data + "</div>").each(function() {
          if($(this).is("div")) {
            // Add the div to the page as a popup.
              close: function() {
              modal: true,
              resizable: false
            // Move the first p to the dialog title. 
            $("#"+dest).dialog( "option", "title", $("#"+dest+">p").first().html() );

            // Update the style of the header.
          } else {
            // Add all other elements to the body directly.
      // Return false so the link isn't clicked.
      return false;

The final step is to go through the page and decorate and links you want to open in dialog popups with the popup attribute. This should be added directly to the A link that will trigger the popup and the href will be be the location to retrieve and place into the popup. The value of the popup attribute needs to be assigned a unique id that will be assigned to the resulting dialog object.

 For example the following link can be make up as so to change it from a normal page link to a popup dialog.
<a href="page2.hmtl">View Page 2</a>
<a popup="page2dialog" href="page2.hmtl">View Page 2 (Popup)</a>

Furthermore the dialog can be accessed and manipulated as needed with the following jQuery selector.

No comments: