javascript: Loading external urls in jqModal jquery plugin

I was introduced two years ago to the jQuery javascript library via the thickbox script which, among other things, allows to load external urls inside a modal window, a neat feature enhancing user experience as it provides a more visual continuity between the current window and the next.
 
jQuery is a surprisingly easy library to get your hands on, even for designers and server-side developers such as me, and as I used it more and more in my every day development, quickly grew in me emotions and feelings of true love towards this splendid library and its outstanding user community. Pop into the mailinglist, you will be amazed by the number of souls dedicated to helping each other. Some politician leaders should learn from it (is there a jquery plugin for solving the everlasting Belgian political crisis ? could be fun :) )

Anyway, among the zillion jquery plugins, one such plugin offers a much more powerful and flexible way to launch modal windows: jqModal.

At first jqModal may not seem as easy to use for novices (unlike thickbox which basically only requires you to add a class to all links that should load into the modal window, thus staying clear of javascript, how convenient). The truth is, once you get your first attempts working, jqModal is just as easy, it just needs the designer to mentally "accept" dealing with a little bit of javascript.

Yet, although quite well documented, the jqModal plugin website does not describe the precise use-case of loading into an iframe, so here is a rundown on how I do it.

The final result of thickbox > jqModal example is in action here

1./ html header:

Include the jqModal script and stylesheet in your header. Make sure you have jquery too !

HTML:
  1. <link rel="stylesheet" type="text/css" media="screen" href="jqModal.css"/>
  2. <script src="jquery-1.2.6.pack.js" type="text/javascript"></script>
  3. <script src="jqModal.js" type="text/javascript"></script>

2./ the html describing the modal window structure

jqModal let you define your own modal window html, and uses special classes, such as .jqmClose, which defines a button with a close functionality. (Note that you don't have to provide the html for the modal layer itself. ) Since we want to load an external url, we will use an IFRAME as container. As a habit, I usually put modal window html code at the very end of the body element.

HTML:
  1. <div id="modalWindow" class="jqmWindow">
  2.         <div id="jqmTitle">
  3.             <button class="jqmClose">
  4.                 Close X
  5.             </button>
  6.             <span id="jqmTitleText">Title of modal window</span>
  7.         </div>
  8.         <iframe id="jqmContent" src="">
  9.         </iframe>
  10.     </div>

3./ the css

Include the jqModal css properties and customize to your liking So, in addition to the jqModal stylesheet, i added this styling:

CSS:
  1. .jqmClose{ background:#FFDD00; border:1px solid #FFDD00; color:#000; clear:right; float:right; padding:0 5px; cursor:pointer; }
  2. .jqmClose:hover{ background:#FFF; } 
  3. #jqmContent{ width:99%; height:99%; display: block; clear:both; margin:auto; margin-top:10px; background:#111; border:1px dotted #444; }

4./ the javascript
Add the following to your $(document).ready event handling function:

JavaScript:
  1. var loadInIframeModal = function(hash){
  2.     var $trigger = $(hash.t);
  3.     var $modal = $(hash.w);
  4.     var myUrl = $trigger.attr('href');
  5.     var myTitle= $trigger.attr('title');
  6.     var $modalContent = $("iframe", $modal);
  7.                    
  8.     $modalContent.html('').attr('src', myUrl);
  9.     //let's use the anchor "title" attribute as modal window title
  10.     $('#jqmTitleText').text(myTitle);
  11.     $modal.jqmShow();
  12. }
  13. // initialise jqModal
  14. $('#modalWindow').jqm({
  15. modal: true,
  16. trigger: 'a.thickbox',
  17. target: '#jqmContent',
  18. onShow:  loadInIframeModal
  19. });
  20.  
  21. });

Basically, the loadInIframeModal function controls what should happen when a jqModal is to be shown: here, it assigns the clicked link's URI to the IFRAME SRC attribute, thus loading the link inside the jqModal iframe, updates the modal title and then reveals the modal.

Then, the jqm() call initializes the jqModal DOM object, specifying that it should be a modal behaviour (nothing clickable outside the window itself), it will be launched by anchor links with class "thickbox", and the result will be loaded in the iframe with id "jqmContent".

It wasn't too difficult wasn't it ? I told you jqModal is flexible. In fact, i think it's the swiss-army knife of all modal windowing !

Converting your website from thickbox to jqModal

I used thickbox on a very large Content Management website, but wanted to get the snappier feel of jqModal.
Not too difficult, except that thickbox parameters are included in the href attribute itself, as additional query vars.

Here is an example of such url:

HTML:
  1. writing.php?todo=display&amp;writing_id=2&amp;KeepThis=true&amp;TB_iframe=true&amp;width=90%&amp;height=99%

In this example, the thickbox parameters are KeepThis,TB_iframe,width and height, which i had to translate into something jqModal could manage. The parameters i was particularly interested in are the "width" and "height", allowing to modify the jqModal window dimensions.

Therefore I created a wrapper function that would look into the querystring for the width and height parameters, and modify the window accordingly.
Note that i wanted the modal window to always stay in the middle of the screen, so redimensioning it means also modifying its position on the screen.
this explains the long code. And also the will to accomodate for percentage resizing (such as in the example above : "width=90%").
Now, it's quite bloated but it works, ok ? :-)

See the thickbox > jqModal example in action here

All suggestions for improvement are welcomed though.

12 OCTOBER 2008 UPDATE: Added a new query vars, that specify if the parent window should be reloaded or not: jqmRefresh (default to true in this case)

JavaScript:
  1. $(document).ready(function(){
  2.         //thickbox replacement
  3.     var closeModal = function(hash)
  4.     {
  5.         var $modalWindow = $(hash.w);
  6.  
  7.         //$('#jqmContent').attr('src', 'blank.html');
  8.         $modalWindow.fadeOut('2000', function()
  9.         {
  10.             hash.o.remove();
  11.             //refresh parent
  12.             if (hash.refreshAfterClose == true)
  13.             {
  14.                 window.location.href = document.location.href;
  15.             }
  16.         });
  17.     };
  18.     var openInFrame = function(hash)
  19.     {
  20.         var $trigger = $(hash.t);
  21.         var $modalWindow = $(hash.w);
  22.         var $modalContainer = $('iframe', $modalWindow);
  23.  
  24.         var myUrl = $trigger.attr('href');
  25.  
  26.         var myTitle = $trigger.attr('title');
  27.         var newWidth = 0, newHeight = 0, newLeft = 0, newTop = 0;
  28.         $modalContainer.html('').attr('src', myUrl);
  29.         $('#jqmTitleText').text(myTitle);
  30.         myUrl = (myUrl.lastIndexOf("#")> -1) ? myUrl.slice(0, myUrl.lastIndexOf("#")) : myUrl;
  31.         var queryString = (myUrl.indexOf("?")> -1) ? myUrl.substr(myUrl.indexOf("?") + 1) : null;
  32.  
  33.         if (queryString != null && typeof queryString != 'undefined')
  34.         {
  35.             var queryVarsArray = queryString.split("&");
  36.             for (var i = 0; i <queryVarsArray.length; i++)
  37.             {
  38.                 if (unescape(queryVarsArray[i].split("=")[0]) == 'width')
  39.                 {
  40.                     var newWidth = queryVarsArray[i].split("=")[1];
  41.                 }
  42.                 if (escape(unescape(queryVarsArray[i].split("=")[0])) == 'height')
  43.                 {
  44.                     var newHeight = queryVarsArray[i].split("=")[1];
  45.                 }
  46.                 if (escape(unescape(queryVarsArray[i].split("=")[0])) == 'jqmRefresh')
  47.                 {
  48.                     hash.refreshAfterClose = queryVarsArray[i].split("=")[1]
  49.                 } else
  50.                 {
  51.                     hash.refreshAfterClose = true;
  52.                 }
  53.             }
  54.             // let's run through all possible values: 90%, nothing or a value in pixel
  55.             if (newHeight != 0)
  56.             {
  57.                 if (newHeight.indexOf('%')> -1)
  58.                 {
  59.  
  60.                     newHeight = Math.floor(parseInt($(window).height()) * (parseInt(newHeight) / 100));
  61.  
  62.                 }
  63.                 var newTop = Math.floor(parseInt($(window).height() - newHeight) / 2);
  64.             }
  65.             else
  66.             {
  67.                 newHeight = $modalWindow.height();
  68.             }
  69.             if (newWidth != 0)
  70.             {
  71.                 if (newWidth.indexOf('%')> -1)
  72.                 {
  73.                     newWidth = Math.floor(parseInt($(window).width() / 100) * parseInt(newWidth));
  74.                 }
  75.                 var newLeft = Math.floor(parseInt($(window).width() / 2) - parseInt(newWidth) / 2);
  76.  
  77.             }
  78.             else
  79.             {
  80.                 newWidth = $modalWindow.width();
  81.             }
  82.  
  83.             // do the animation so that the windows stays on center of screen despite resizing
  84.             $modalWindow.css({
  85.                 newWidth,
  86.                 height: newHeight,
  87.                 opacity: 0
  88.             }).jqmShow().animate({
  89.                 newWidth,
  90.                 height: newHeight,
  91.                 top: newTop,
  92.                 left: newLeft,
  93.                 marginLeft: 0,
  94.                 opacity: 1
  95.             }, 'slow');
  96.         }
  97.         else
  98.         {
  99.             // don't do animations
  100.             $modalWindow.jqmShow();
  101.         }
  102.  
  103.     }
  104.  
  105.     $('#modalWindow').jqm({
  106.         overlay: 70,
  107.         modal: true,
  108.         trigger: 'a.thickbox',
  109.         target: '#jqmContent',
  110.         onHide: closeModal,
  111.         onShow: openInFrame
  112.     });
  113. });

body

    <body>
<!-- HEADER -->
<div id="header">
<h1>Thickbox to jqModal example</h1>
</div>
<!-- end HEADER -->
<div id="main">
<p>
            Let's see what <a href="http://www.google.com/search?q=jqmodal&width=90%&height=50%&jqmRefresh=false" class="thickbox" title="g00gle knows it all">google thinks</a> of jqModal !
</p>
<p>
And what does <a href="http://search.live.com/results.aspx?q=jqmodal&go=&form=QBLH&width=50%&height=80%&jqmRefresh=true" title="Bill is in da House" class="thickbox">MSN Live</a>
think of <a class="thickbox" href="http://dev.iceburg.net/jquery/jqModal/?width=79%&height=90%" title="The swiss-army knife of a modal world">jqmodal</a>? Wooh, a lot !
</p>
        <p>
This one will refresh the page when you close it: <a href="http://www.google.com/search?q=love&width=90%&height=50%&jqmRefresh=true" class="thickbox" title="g00gle knows it all">try it</a> !
</p>
<p>
If you wonder what this page is about, how about <a title="jqModal iframe mode explained" href="http://www.pixeline.be/blog/2008/javascript-loading-external-urls-in-jqmodal-jquery-plugin/?width=95%&height=80%" class="thickbox">reading the dedicated blog post</a>
?
</p>
<p><a href="test_closebutton.html?width=250&height=150" class="thickbox" title="page with close button">This page</a> contains a "close" button, try it!</p>

</div>
<!-- end MAIN -->
</div>
<div id="modalWindow" class="jqmWindow">
<div id="jqmTitle">

            <button class="jqmClose">
X
</button>
<span id="jqmTitleText">Title of modal window</span>
</div>
<iframe id="jqmContent" src="">
</iframe>
</div>
</body>