简体   繁体   中英

Get div height befor the div content is fully loaded

I've got a button, that when I click executes a js code. Like this.

jQuery( ".button" ).on('click', function(){  
    var page = jQuery(this).attr('data-href');//Get data-href with permalink.
    jQuery('#ajax_div').load(page, 
    function(){ 
        var newHeight = jQuery('#content_loaded').height()+200;
        var el = jQuery('#div_containing_ajax_div_and_content_loaded');
        el.css({'height': newHeight + 'px'});
    });

});

The first time it loads the page works wrong, but after have the images, etc, in cache it works ok. How can I wait that the content is fully rendered to execute the height calc? All of this without use delay functions and with out use a plugin. There is a function like $(windows).ready().

I'm using wordpress, and with jquery load() it gets the height before the image is fully render and the height is less than the real height of the content in the div.

Thanks.

You could check that all images added are loaded using following snippet:

jQuery(".button").on('click', function () {
    var page = jQuery(this).attr('data-href'); //Get data-href with permalink.
    jQuery('#ajax_div').load(page, function () {
        var $self = $(this),
            $contentImages = $(this).find('img');
        $contentImages.one('load', function () {
            $(this).addClass('loaded');
            if ($self.find('img.loaded').length === $contentImages.length) {
                var newHeight = jQuery('#content_loaded').height() + 200;
                var el = jQuery('#div_containing_ajax_div_and_content_loaded');
                el.css({
                    'height': newHeight + 'px'
                });
            }
        }).each(function () {
            if (this.complete) $(this).triggerHandler('load');
        });
    });

});

maybe I should say that you have 2 ways to do that .. one I'm not tested it and another I tested it

1st: untested way .promise().done();

jQuery('#ajax_div').load(page).promise().done(function(){
    // var newHeight ......
});

2nd: tested way in .load callback function loop through images and check if loaded or not using Image.error(function() {});

$('img').each(function(){
        var Image = $(this);
        var GetSrc = $(this).attr('src');
        Image.error(function() {
            // newHeight ......
        });
 });

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM