Currently, I am in the process of developing a jQuery script that will automatically adjust the size and position of image elements upon page load or resize. To structure my layout, I am utilizing Bootstrap and have set a fixed height using CSS. It is worth mentioning that once development is complete, I will not have the ability to control the images' sizes or aspect ratios.
After successfully creating a local script that handles the calculations and conditional statements for images of varying dimensions and aspect ratios, I now need to encase it within a jQuery each()
loop.
My attempts at implementing a single loop surrounding the main script targeting elements with the .listing-box
class were met with mixed results. Adding a nested loop to target the actual image inside led to unintended consequences where initial calculations were applied to all subsequent images. My struggle lies in properly incorporating the each()
function.
HTML
<div class="row">
<div class="col-sm-3">
<a href="#">
<div class="listing-box">
<div class="listing">
<img src="http://placehold.it/600x400" alt="thumbnail" class="thumb">
</div>
</div>
</a>
</div>
</div>
CSS
.listing-box {
width: 100%;
height: 220px;
position: relative;
overflow: hidden;
}
.thumb {
overflow: hidden;
}
jQuery
$(window).on('resize load', function() {
// get .listing-box width and height
var boxWidth = $(".listing-box").width();
var boxHeight = $(".listing-box").height();
var boxAspect = (boxWidth / boxHeight);
// get .thumb width and height
var imgWidth = $(".thumb").width();
var imgHeight = $(".thumb").height();
var imgAspect = (imgWidth / imgHeight);
// set some empty variables
var newWidth,
newHeight,
mTop,
mLeft;
if (imgAspect < 1) {
// image is VERTICAL
// assign values
newWidth = boxWidth;
newHeight = newWidth * imgHeight / imgWidth;
mTop = (newHeight - boxHeight) / 2;
// use new values for inline css
$(".thumb").css({
width: newWidth + "px",
height: newHeight + "px",
marginTop: "-" + mTop + "px"
});
} else {
// image is HORIZONTAL
if (imgAspect > boxAspect) {
// image is wider than taller
// assign values
newHeight = boxHeight;
newWidth = newHeight * imgWidth / imgHeight;
mLeft = (newWidth - boxWidth) / 2;
// use new values for inline css
$(".thumb").css({
width: newWidth + "px",
height: newHeight + "px",
marginLeft: "-" + mLeft + "px"
});
} else {
// image is taller than wider
// assign values
newWidth = boxWidth;
newHeight = newWidth * imgHeight / imgWidth;
mTop = (newHeight - boxHeight) / 2;
// use new values for inline css
$(".thumb").css({
width: newWidth + "px",
height: newHeight + "px",
marginTop: "-" + mTop + "px"
});
}
}
});
Although there are various plugins available for this purpose, I am determined to achieve this without relying on any external resources. My primary obstacle lies in effectively implementing looping functionalities.