IE Max-Height and Overflow:auto Hack Using JQuery

I use JQuery on everything––on my coffee, on my bread, and even to fix IE. I was posting FCBKcomplete ColdFusion wrapper a few hours ago when I noticed my code coloring box acting strangely inside IE. It worked fine in FireFox, and Chrome worked beautifully as well. I use max-height:500px; overflow:auto; white-space:nowrap. All I wanted was the scroll bar to display ONLY if the height of my code box contents were more than 500px. If the height was less, leave the height alone! Apparently, it was just too much to ask of IE. If horizontal overflow becomes true, IE forces my div up to max-height, 500px. If I have a single line of text overflowing horizontally, it becomes a huge, ugly, empty white box, 500px tall. It has been 40 years since the moon landing, 100 years since the Model T, and yet IE still can not do a max-height right.

Here is a quick look at a JQuery hack that works around this issue. I know it is not very pretty, but it will stop you from drowning inside this IE bug.

   1: IEmaxHeightFix('.codeblock','500')

Pass your CSS selector to the first position, and then Class or ID or any other JQuery Selectors, along with the max-height, go to the second position. Here is the code, which uses JQuery.

   1: function IEmaxHeightFix(selector,size){
   2:  if($.browser.msie){
   3:  $(selector).each( function() {
   4:     var wraper = $('<div></div>').css({margin: 0, padding: 0});
   5:     $(this).wrapInner(wraper);
   6:     var realhight = $(this).children('div').innerHeight();
   7:     if (realhight < size && $(this).children('div').textWidth() > $(this).width()) {
   8:     $(this).height( realhight + 18 );
   9:     }
  10:     wraper.remove();
  11:  } )
  12:  }
  13: };
  14: $.fn.textWidth = function(){
  15:  var html_org = $(this).html();
  16:  var html_calc = '<span>' + html_org + '</span>'
  17:  $(this).html(html_calc);
  18:  var width = $(this).find('span:first').width();
  19:  $(this).html(html_org);
  20:  return width;
  21: };
Show/Hide Line Numbers . Full Screen . Plain

Thanks StackOverflow for textWidth() function.