Scaling image to fit container while keeping aspect ratio with jquery -
i've been trying scale images fit parent container. here's code:
markup
<ul class="slides"> <li class="scale"><img src="<?php echo $attachments->src('full'); ?>" /></li> <li class="scale"><img src="<?php echo $attachments->src('full'); ?>" /></li> <li class="scale"><img src="<?php echo $attachments->src('full'); ?>" /></li> <li class="scale"><img src="<?php echo $attachments->src('full'); ?>" /></li> <li class="scale"><img src="<?php echo $attachments->src('full'); ?>" /></li> </ul>
css
.fullwidth { width:100%; height:auto; } .fullheight { width:auto; height:100%; }
js
$('.scale img').each(function(){ var img = $(this); if (img.height() < img.width()){ img.addclass('fullwidth'); } else { img.addclass('fullheight'); } });
what's weird although images portrait , landscape, js gives images fullheight
class. want images scale , resize it's parent does, parents use percentage dimensions. i've tried many plugins none seem work me. got idea?
unless waiting images finish loading, .height()
, .width()
not return proper values values valid when image has loaded. if both return 0 or undefined, fullheight class on of them.
the solution here use onload handlers , set class when image loaded. because images in markup may load before js runs (particularly if in browser cache), either have check if image loaded , use it's height , width if loaded or, if not loaded yet, need set onload handler. or, can assign onload handler in markup onload you're sure load handler installed before loads.
here's 1 way checks see if image loaded , adapts based on that:
$('.scale img').each(function(){ function setclass() { var img = $(this); if (img.height() < img.width()){ img.addclass('fullwidth'); } else { img.addclass('fullheight'); } } // if image loaded, can set class if (this.complete) { setclass.call(this); } else { // otherwise, must set class in load handler when loaded this.onload = setclass; } });
if can modify markup, can has advantage of it's set image loads:
markup:
<ul class="slides"> <li class="scale"><img onload="scaledynamic()" src="<?php echo $attachments->src('full'); ?>" /></li> <li class="scale"><img onload="scaledynamic()" src="<?php echo $attachments->src('full'); ?>" /></li> <li class="scale"><img onload="scaledynamic()" src="<?php echo $attachments->src('full'); ?>" /></li> <li class="scale"><img onload="scaledynamic()" src="<?php echo $attachments->src('full'); ?>" /></li> <li class="scale"><img onload="scaledynamic()" src="<?php echo $attachments->src('full'); ?>" /></li> </ul>
code:
// must global function function scaledynamic() { var img = $(this); if (img.height() < img.width()){ img.addclass('fullwidth'); } else { img.addclass('fullheight'); } }
fyi, if of these images might visible load, may want set default style visibility: hidden
, when finish loading, set style visibility: visible
when you've set scaling class , image loaded.
Comments
Post a Comment