William's profileBill PierceBlogLists Tools Help

Blog


    3/16/2006

    Resizing a window using Javascript

    Lets say you wanted to resize your window to fit an element on your page (like a table).  The code below should achieve that for you.  Tested in FF and IE6:
    function resizeWindowToElement(sElementId, bSecondResize)
    {
      var dx, dy, el;
      var wWidth, wHeight;
      
      el = document.getElementById(sElementId);
      
      if( el )
      {
        if( typeof( window.innerWidth ) == 'number' ) 
        {
          //Non-IE
          wWidth = window.innerWidth;
          wHeight = window.innerHeight;
        } 
        else if( document.documentElement && 
                   ( document.documentElement.clientWidth ||
                     document.documentElement.clientHeight ) ) 
        {
          //IE 6+ in 'standards compliant mode'
          wWidth = document.documentElement.clientWidth;
          wHeight = document.documentElement.clientHeight;
        } 
        else if( document.body && 
                   ( document.body.clientWidth || 
                     document.body.clientHeight ) ) 
        {
          //IE 4 compatible
          wWidth = document.body.clientWidth;
          wHeight = document.body.clientHeight;
        }
        
        dx = el.offsetWidth - wWidth;
        dy = el.offsetHeight - wHeight;
        
        window.resizeBy(dx, dy);
        
        // Resizing the window can cause menu bars to 
        // re-arrange themselves and block content.
        // Resize again to accomodate this
        if( !bSecondResize )
        {
          resizeWindowToElement(sElementId, true);
        }
      }
    }