Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery height() function returning inaccurate value

Tags:

jquery

height

I'm using jQuery to measure the height of two divs (after document load) and then making the shorter div equal to the height of the taller div. However one of the div has an image in it, and it seems to be measure the height of the div as if the image isn't there (if I remove the image after everything has loaded, the height is accurate). Here is my code:

$(document).ready(function() {
    var rheight = $('#random').height();
    var qheight = $('#quote').height();
    if(rheight > qheight) $('#quote').height(rheight);
    else $('#random').height(qheight);
}
like image 480
jetlej Avatar asked Oct 23 '11 08:10

jetlej


2 Answers

If you measure the <div> before the image has finished loading, its height won't be taken into account. You can wait for the image to be ready using a load event handler:

EDIT: The load event handler can be registered on the window object itself to avoid the reliability pitfalls pointed out by Chris:

$(window).load(function() {
    var rheight = $("#random").height();
    var qheight = $("#quote").height();
    if (qheight > rheight) {
        $("#quote").height(rheight);
    } else {
        $("#random").height(qheight);
    }
});
like image 198
Frédéric Hamidi Avatar answered Nov 17 '22 01:11

Frédéric Hamidi


If you know the height of the image in advance, you can set the image tag's height attribute. This will allow the browser to render the div at the correct height before the image loads, which means your height checks should work as expected.

Hooking the load event using jQuery can be problematic, according to its documentation. Apparently the event "can cease to fire for images that already live in the browser's cache".

like image 36
Red Orca Avatar answered Nov 17 '22 00:11

Red Orca