lummycoder
lummycoder

Reputation: 608

How to get height of element with dynamically loaded images inside

    I have a lot of tables and in last td in last tr I put message from back-end. There could be not only text, but the images (url to them in tags), so they load dynamically. I need to get the height of this table and if it more than 400 I add some contant.

    Firstly, I did this:

$("table[name]='forum'").each(function() {
        var height = $(this).height();
        if (height > 400) {
            var redirect = $("#backUrl").val() + "#" + $(this).find("[name]='answ'").attr("id");
            $(this).find("tr:last-child > td:last-child").append(function() {
                return "<div></div><a style='float: right' href='"+ redirect + "'><img src='/images/arrow_up.png'></a>";
            });
        };
    });

    But it didn't work for tables with images. Than I googled that for img I should use load() and add:

$(this+"> img").load(function() {
     height += $(this).height(); 
});

but I understand, that this is wrong, cause img could be loaded after this block is done. I did some other actions, but it won't affect as I wanted.

    What is the solution of this problem? Because it calculates height of whole element without img tag.

Upvotes: 0

Views: 747

Answers (2)

Andrew
Andrew

Reputation: 5340

To get the final table height(if the img will affect the height, or you can pre-set some max height maybe), you must wait all images loaded.

var table = $(this), imgs = table.find("img"), len = imgs.length;

imgs.one('load', function() {

    len--;

    //now all image loaded
    if (len == 0) {

        //here you got the final height
        height = table .height();

        //do stuffs here
    }

}).each(function() {

    if (this.complete)
        $(this).load();
});

Upvotes: 1

Rituraj ratan
Rituraj ratan

Reputation: 10378

$(this).find("img").load(function() {
     height += $(this).height(); 
});

Upvotes: 1

Related Questions