Maintain aspect ratio on browser window resize?

Posted by Anthony on Stack Overflow See other posts from Stack Overflow or by Anthony
Published on 2010-03-21T07:38:02Z Indexed on 2010/03/21 7:41 UTC
Read the original article Hit count: 474

Filed under:
|
|
|

I have a simple page with images, and when the user clicks the image, it opens up a new browser window with the image filling the area. I have the css set on the new window so that the image height and width are both 100% (and overflow is set to hidden) so that the window can be resized.

But what I need is for the window to maintain aspect ratio if the user resizes it. Right now, I'm stuck because I'm not getting how the event works, but I think I'm making this harder than it needs to be. Right now I have:

$(function(){
    $(window).resize(function() {
        var height = $(this).attr("innerHeight");
        var width = $(this).attr("innerWidth");
        if(height/width != .75){
            window.resizeTo(width,width*.75);
        }
    });
});

Before I added the conditional, the window would immediately start shrinking (apparently opening a new window fires the resize event). Adding the conditional preventing this from happening when the window opens, but any resizing starts the shrinking again.

Is it just because the height and width are never exactly the right ratio (should I manually set the width to a round number ever time) or is there something else I'm doing wrong? Or is there some other way to get what I'm after that's more straightforward?

© Stack Overflow or respective owner

Related posts about html

Related posts about browser