I am trying to scale images to fit within their parent element width, and especially for images located in tables.
The problem was that different browsers and platforms seem to behave differently when it comes to determining the width of the parent element.
So I tried to get the width of the parent td element in $(document).ready:
$('td').each(function () {
var width = $(this).width();
$(this).width(width);
});
And then in $(window).load (when the images should be loaded) I try to set the width of the images according to the width css style of the td:
var parentWidth = $(this).parent().width();
if ($(this).closest('td')) {
parentWidth = $(this).closest('td').css('width').replace('px', '');
}
But this seems to be unreliable. It works sometimes, and in some browsers, but sometimes it fails miserably, giving the wrong value for the td width.
I want to be able to get the width of the td before the images are loaded, so that the width isn’t distorted by the images expanding it.
Of course, none of this would have been necessary, if it wasn’t for IE8 and below not supporting max-width and max-height, but it doesn’t.
How can I do this and get the parent widths before images are loaded?
BTW: the td can have a width percentage value to start with in a 100% width table.
This line is incorrect:
closest returns a jQuery object with 0 or 1 element. You probably mean: