I am trying to accomplish two things:
The main content div will be dynamically sized to fit the exact height of the window. I accomplish that goal with this function:
$(document).on( 'ready', function() { panelsResize(); $(window).on( 'resize', panelsResize ); }); function panelsResize() { var screenHeight = $(window).height(); var screenWidth = $(window).width(); if (screenWidth > 768) { $( ".panels" ).css( "height", screenHeight ); } };
The class .panels
is applied to the main content area.
This works swell.
- I am trying to fill the
.panels
with the images in.large
. These images need to retain aspect ratio while being scalable. I have based my code on this answer.
This works, but not on ready. I have to resize the screen, dropping below the media query that switches the display for .large
to none. When I resize to the higher media query, switching display to block, the functionality works perfect.
Any ideas?
Here's the function (and markup):
$(document).on( 'ready', function() {
bgResize();
$(window).on( 'resize', bgResize );
});
function bgResize(){
$( '.large' ).each(function() {
var th = $(window).height(),//box height
tw = $(window).width(),//box width
im = $(this).children('img'),//image
ih = im.height(),//inital image height
iw = im.width();//initial image width
if ( iw < tw ) {
im.css( { "width" : "100%", "height" : "auto" } );
}
else if ( ih < th ) {
im.css( { "height" : "100%", "width" : "auto" } );
}
var nh = im.height(),//new image height
nw = im.width(),//new image width
hd = (nh-th)/2,//half dif img/box height
wd = (nw-tw)/2;//half dif img/box width
if (nh<nw) {
im.css({marginLeft: '-'+wd+'px', marginTop: 0});//offset left
} else {
im.css({marginTop: '-'+hd+'px', marginLeft: 0});//offset top
}
});
};
This is the HTML:
<ul id="homePanels">
<li id="cat1" class="panels">
<div class="large">
<img src="#" alt="" />
</div>
<div class="small">
<img src="#" alt="" />
</div>
</li>
</ul>
The CSS:
#homePanels {
list-style: none;
margin:0;
padding:0;
overflow: hidden;
}
.large {
width:100%;
height:100%;
}
@media (min-width: 768px) {
.large{display: block;}
.small{display:none}
}
@media (max-width: 768px) {
.small {display:block;}
.large {display:none;}
}