I was working on script which resizes images to fit container size. I wrote down the following code:
$(function () {
$('.postbody .content img').each(function () {
var containerWidth = $(this).parent().width();
if ($(this).width() > containerWidth) {
$(this).width(containerWidth);
$(this).wrap('<a href="' + $(this).attr('src') + '" target="_blank"></a>');
}
});
});
But it only worked for the first element in loop. With my previous experience with issues following assigning jQuery methods to a variable I changed the code a bit:
$(function (){
$('.postbody .content img').each(function () {
if ($(this).width() > $(this).parent().width()) {
$(this).width( $(this).parent().width() );
$(this).wrap('<a href="'+$(this).attr('src')+'" target="_blank"></a>');
}
});
});
And now it works perfectly. But I cannot figure out how. Shouldn't the containerWidth variable get new value with each function call by the each loop?
EDIT: Please note that all containers are equal size.
$(window).load()event. As by that time all the images are loaded. Hence the parentdivgets it width. I think the issue is with the event and not with the variable.