Reputation: 44363
hey guys, i wonder how to solve this:
function setimgwidth() {
var bw = $('.post-body').width();
$(".post-body p img").each(function() {
var os = $(this).width();
//if (bw < os) {
$(this).removeAttr('height');
$(this).width(bw);
//}
});
}
basically my .post-body div is dynamically asdjusted to the screensize. every image inside of it should as well be resized to the width of the .post-body div, but only if the .post-body is NOT larger than the original size of the image. i don't want the image to get blurry.
as for now it actually works almost like i want it to. the function is called on window resize. however if the .post-body is larger than the actual image-size the image gets still enlarged.
if I uncomment the code above it seems to work, but only if i resize the window to a smaller size. if it's resized larger the image will not adjust anymore and stay small. that's probably because the original size gets overwritten every time i call the function.
somehow i can't find a proper solution and i need your help, please. thank you in advance, matt
Upvotes: 0
Views: 3586
Reputation: 5349
The problem that you are having when trying to resize the window to make it larger (and hence the div and hence the image) is that the original image size is being lost.
The following code needs to run after the DOM has loaded and the images have width (may need to happen after .load()
)
$(".post-body p img").each(function() {
// Save the original image width
$(this).data('width', $(this).width());
});
The folowing code needs to run on the window resize event (like you currently do):
function setimgwidth() {
var bw = $('.post-body').width();
$(".post-body p img").each(function() {
// Check the width of the original image size
if (bw < $(this).data('width')) {
$(this).removeAttr('height');
$(this).width(bw);
}
});
}
Upvotes: 1
Reputation: 11159
You need to make sure you're measuring the image's width after it has loaded. So if you just try $('#my-img').width()
in normal jQuery code, it'll probably return 0 (unless you have the width attribute or the width style set) because the ready event doesn't wait for images to have loaded. $('#my-img').load(function () { /* do something */ });
should do it.
Upvotes: 0