rgraphix
rgraphix

Reputation: 71

jquery 1.8 and higher, set the height of a div to the same as another div

As of Jquery 1.8 a change was made when getting the height() of an element. I have a CSS div height set to auto with the image inside dictating the height and width of the div by using % and auto), and when the window loads i use Jquery to get the height of the element and make another div next to it the same height. After researching this I have noticed that it is returning the height before the CSS has set the new height that is set by the image. 1.7 allowed this, but 1.8 and up does not. Is ther a work around. this is the css

 #element1{ width:80%; height:auto;}
 #element1 img{width:100%; height:auto};//this allows the image to resize with the page responsively.

jQuery...

$(window).ready(
function(){
var x = $("#element").height();
alert(x); // this would return what the height was dynamically set as by the css in 1.7, but 1.8 returns a small number that i am pretty certain is just the padding added to 0px
});

Hopefully this makes sense, and someone has a work around. Thanks

Upvotes: 0

Views: 315

Answers (2)

Terry
Terry

Reputation: 66093

Instead of listening on $(window).load(), which might stall proper height assignment until all resources have been successfully loaded, you can listen to successful loading on each <img> instance and trigger proper height calculation.

However since in your question you only have one element you are concerned with setting height dynamically, I have reduced my script without the need to loop through all <img> instances on the page. Assuming that you have the following markup:

<div id="element1">
    <img ... />
</div>

You can create a new image, check if it is loaded and then instruct jQuery to run the height calculations and set a new height when this is done:

$(function() {
    var $img = $('<img />', {
        'src': $('#element1 img').attr('src')
    });

    $img.load(function() {
        $('#element2').css('height', $('#element1').height());
    });
});

Upvotes: 1

Jeff Howard
Jeff Howard

Reputation: 344

There's a mismatch between your css selector (#element1) and your jquery selector ('#element'). Start by making them both match whatever you have on your html element. You could also wrap this in a timeout so your image will have time to fully load.

$( document ).ready(function() {
    setTimeout(function() {
        $('#element2').height( $('#element1').height() );
    }, 2000});
});

Upvotes: 0

Related Questions