Doorknob Doorknob - 3 months ago 30
Javascript Question

Scale image properly but fit inside div

I am making an image gallery. This is the HTML for the image:

<div style="width: 84%; height: 100%; float: left; text-align: center;"><img
id="mainimage" style="height: 100%;"
src="http://www.gymheroapp.com/workouts/img/spinner.gif"/></div>
<!-- Loading spinner is temp image, will be replaced by Javascript later -->


It works fine when the image is square, or the width is not too much more than the height. It breaks when the width is too great, though. Example of image overflowing:

image overflowing

Is there a way I could check whether there is overflow within my Javascript? Something like this:

image.setAttribute('height', '100%')
image.removeAttribute('width')
if (image.isOverflowing()) {
image.setAttribute('width', '100%')
image.removeAttribute('height')
}


Even better, is there any way to scale the image properly but fit it withing the containing
div
?

Answer

jquery example

Best fit:

$('img').on('load',function(){
    var css;
    var ratio=$(this).width() / $(this).height();
    var pratio=$(this).parent().width() / $(this).parent().height();
    if (ratio<pratio) css={width:'auto', height:'100%'};
    else css={width:'100%', height:'auto'};
    $(this).css(css);
});

Edit to account for caveat where image is in cache

$('img').on('bestfit',function(){
    var css;
    var ratio=$(this).width() / $(this).height();
    var pratio=$(this).parent().width() / $(this).parent().height();
    if (ratio<pratio) css={width:'auto', height:'100%'};
    else css={width:'100%', height:'auto'};
    $(this).css(css);
}).on('load', function(){
    $(this).trigger('bestfit');
}).trigger('bestfit');