Javascript – resizing a window to fit the contents

Recently we’ve been faced with the question of how to resize the browser window opened with javascript window.open so that when the content is changed, the window would resize, and we never had to see the vertical scrollbar. Yes, that’s what the numerous lightboxes do, but we didn’t want a lightbox, we wanted a usual browser window (reasons are not relevant here).

What else we had except good ole JS: we have jQuery.
What limitations we have: IE8. We have to support it.

So, the first solution that comes to mind is, get the last visible element, get its position, and try to calculate the needed window height based on this. Like that:

    var lastEl = $(":visible:last");
    var width = $(window).width();
    var height = lastEl.position.top() + lastEl.height + 30; // last figure is just some margin
    window.resizeTo(width, height);

Unfortunately, we discovered that it doesn’t work as intended. Yes, the window was resized, but each time the scroll was still visible. We tried to use $(document).height() instead of our lastEl calculation, because the spec says that it shows the whole doc height, not just the visible viewport, but still no luck. We still had that scroll, and it looked like we needed to add another variable to our sum: the difference between window.innerHeight and window.outerHeight.

But these two properties don’t come till IE9!

So, what worked in the end was this small code snippet:

    var w = $(window), d = $(document), b = $('body');
    window.resizeBy(0, ((b.height() - w.height()) || d.height() - w.height()));

You just had to call it when all the data is loaded to the view, so that the view has its final dimensions.

Advertisements

About Maryna Cherniavska

I have productively spent 10+ years in IT industry, designing, developing, building and deploying desktop and web applications, designing database structures and otherwise proving that females have a place among software developers. And this is a good place.
This entry was posted in Uncategorized and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s