Gregor Gregor - 4 months ago 14
Javascript Question

How to get the height of a div after its content is loaded?

im trying to get the size of an

<img>
in the
<window>
by checking width and height of its container.

i used
.load()
to wait until the
<img>
is loaded.

On pageload the size is still 0.

I only get the correct height on resize.

What is wrong here?

$(document).ready(function(){
$('img').load(function(){
function size(){
var height = $('#size').height();
var width = $('#size').width();
$('#size').find('p.size').remove();
$('#size').append('<p class="size">' + height + '-' + width + '</p>');
};
$(window).load(size);
$(window).resize(size);
});
});

Answer

you define a function, but you don't invoke it

place size(); after $(window).resize(size);

EDIT: whole code with some improvements

$(document).ready(function(){
    function size(){
        var height = $('#size').height();
        var width = $('#size').width();
        $('#size').find('p.size').remove();
        $('#size').append('<p class="size">' + height + '-' + width + '</p>');
    }

    $(window).load(size);
    $(window).resize(size);
    $('img').load(size);
});