[JQuery] Replace IMG tags with DIV tags instead to Resize/Scale Proportionally

access_time Tuesday, April 22, 2014 12:01 pm
account_circle Andy Boot

HTML:

We apply class=”resizeDivProportionally” to target specific Div elements on our page:

<script src=”js/jquery-1.11.0.min.js” type=”text/javascript”></script>
<div id=”Container”>
<div id=”Promo” class=”resizeDivProportionally”></div>
</div>

CSS:

#Container{position:relative;z-index:-10;}

#Promo{
max-width:1000px; /*Set the image width*/
max-height: 355px; /*Set the image height*/
background-image: url(“images/Promo.jpg”);
background-size: contain;
background-repeat: no-repeat;
}

JQuery:

$(document).ready(function () {

resizeDivProportionally();

$(window).on(‘resize’, function(){resizeDivProportionally()});
})

function resizeDivProportionally(){
$(“div”).each(function(){
var maxWidth = $(this).css(‘max-width’).replace(“px”,””);
var maxHeight = $(this).css(‘max-height’).replace(“px”,””);
var width = $(this).width();
var height = $(this).height();

if ($(this).hasClass(“resizeDivProportionally”)){
if(width < maxWidth){
$(this).css(“height”, Math.ceil(maxHeight / maxWidth * width));
}
else{$(this).css(“height”, maxHeight);}
}

});
}

FYI – The formula for working out the size of a scaled image is original height / original width x new width = new height

Conclusion:

Why do we need to do this? – To put it simply, you don’t really have to, however I created this with the goal to replace statically set images on my page and give the control of the image source and size to my CSS instead. By doing so, I am able to replace the image used based upon the device rendering the page. In my example above, I wouldn’t want an image of 1000px wide to be downloaded on an iPhone with a much smaller resolution. We can control what gets rendered on what device/resolution using CSS media queries.