Tuesday, 15 February 2011

jQuery Colorbox - resizing iframe to match content

The designers and HTMLers I work with are a pernickety bunch, and rightfully so. Quite often they want a lightbox-type overlay for a form that can vary in size depending on what selections the user makes in the form, and when the form is submitted a small thank you message is displayed. They want the overlay to resize itself when the content changes.

Until recently we were using colorbox with divs, not iframes, as there was seemingly no way of resizing the iframe to match content. The knock-on effect of this was a whole heap of trouble trying to avoid postbacks of the overlay content as the parent page would postback too.

Using an iframe would make things so much easier technically as we could postback all we wanted in our overlay, opening up the opportunity for server-validation, pagination, file uploading etc, without posting back the parent page. And so it was that I looked into iframe resizing.

I achieved this using colorbox v1.3.9, and assume it works on later versions. Working code is available on my github here. In summary, drop this code into your jquery.colorbox.js file just before the publicMethod.resize function:
publicMethod.myResize = function (iW, iH) { 
 if (!open) { return; }
 if (settings.scrolling) { return; }
 var speed = settings.transition === "none" ? 0 : settings.speed;
 $window.unbind('resize.' + prefix);
 settings.w = iW;
 settings.h = iH;
 $loaded.css({ width: settings.w, height: settings.h });

And then in your iframe content page use the following:

jQuery(document).ready(function (){
 jQuery(window).bind("load", function () {
 var frameWidth = jQuery(document).width();
 var frameHeight = jQuery(document).height() + 20;
 parent.$.fn.colorbox.myResize(frameWidth, frameHeight);
This solution was adapted from a post found on the Google colorbox group.

Friday, 11 February 2011

Escaping a curly bracket in string.format

This doesn't work because the curly brackets (or braces) aren't escaped:
newStr = string.Format("{Hello {0}, in curly braces}", yourName);
Do we need to escape the brackets with a backslash like this? No, it doesn't work:
newStr = string.Format("\{Hello {0}, in curly braces\}", yourName);
Seems strange, but you need to escape your curly brackets with another one like, this:
newStr = string.Format("{{Hello {0}, in curly braces}}", yourName);