I am trying to make an image resize based on the browser size changes using JQuery.
My goal is for the image to scale without losing its aspect ratio or getting cropped.
I have incorporated Bootstrap in my HTML structure:
<div class="container-fluid">
<div class="row">
<div class="col-sm">
<div class="text-block">
<h1>Hello World</h1>
<h6>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</h6>
</div>
</div>
<div class="col-sm img-container">
<img src="image.png" />
</div>
<div class="col-sm">
<div class="text-block">
<h6>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</h6>
</div>
</div>
</div>
</div>
The image is contained within the .img-container
div and my JQuery implementation is as follows:
$(document).ready(function() {
$(window).resize(function() {
var img = $("img");
var image = $(".img-container").find(img);
var browserRatio = $(this).width() / $(this).height();
var imageRatio = image.width() / image.height();
if(browserRatio > imageRatio) {
$(".img-container").find(img).css({ "width": "100%", "height": "auto"});
}
else if(imageRatio > browserRatio) {
$(".img-container").find(img).css({ "width": "auto", "height": "100%"});
}
console.log("Browser ratio is :" + browserRatio);
console.log("Image ratio is:" + imageRatio);
});
});
I aim to adjust the image's dimensions by comparing the ratios of the browser and the image, but it's not functioning correctly. The image width does not retain its original ratio. What could be the issue with my code?