Reputation: 147
I have the background of a section with the ID named home set as an image. The image has an aspect ratio of 1.5. I've written some very basic javascript to ensure that when the window size is changed, the section scales per the aspect ratio of the image. Inside of that section I have content in a div with the class container. This content is of a certain vertical height. The basic javascript I have written doesn't allow the height of the section to be less then that of the content. Hence, at that point the section stops scaling with the window size. The problem I am having is that when you scale the window past that point and then back, the section doesn't scale back up.
I've created a fiddler to help explain. http://jsfiddle.net/Chadimoglou/Bpryg/ I recommend testing it in mobile mode. To recreate what I'm doing, have the window go full screen. Grab a bottom corner and resize a little to see the background resize with the aspect ratio. Then resize so it's smaller then the height and width of the red content box. After that, pull back out again and you should see the issue I'm having. Below is a snippet of my javascript.
$(document).ready(function() {
var theWindow = $(window),
aspectRatio = 1920 / 1280;
function resizeBg() {
$("#home").width(theWindow.width);
if( ( $("#home").width()/aspectRatio ) < $("#home > .container").height() ) {
$("#home").width( $("#home > .container").height()*aspectRatio );
}
$("#home").height($("#home").width()/aspectRatio);
}
theWindow.resize(resizeBg);
window.onload=resizeBg();
});
Thanks kindly in advance for any help.
Upvotes: 2
Views: 3989
Reputation: 10908
I'm not a good JS coder, but going with the logic :
To keep the aspect ratio you could modify the CSS with JS : How to preserve aspect ratio when scaling image using one (CSS) dimension in IE6?
To know whether you should set the height or the width on auto, you'll need to know if the screen size is larger than your image or taller than you image on the aspect ratio. Just compare the two aspect ratio, then you'll know which one will be on auto. Like that, you image will never leave an unfilled part on your background and will expand to it's full width or it's full height, depending on the client aspect ratio and your image aspect ratio.
You can use :
document.documentElement.clientWidth
and
document.documentElement.clientHeight
to get the client window size and calculate the aspect ratio.
Upvotes: 1
Reputation: 206102
$(function() {
var $w = $(window),
$h = $('#home'), // CACHE YOUR SELECTORS
aspectRatio = 1920 / 1280;
function resizeBg() {
$h.width($w.width()); // YOUR ERROR ( should be width() )
if( ( $h.width()/aspectRatio ) <= $("> .container", $h).height() ) {
$h.width( $(" > .container", $h).height()*aspectRatio );
}
$h.height( $h.width()/aspectRatio);
}
$w.resize(resizeBg);
$w.onload=resizeBg();
});
Upvotes: 1