Pergunta

:) I have a little problem:

I have a div, and inside it, I have two divs, one next to the another. The one of the left varies its height to keep its relation with its width while resizing, and I want the one of the right to have the same height that the left one; I have this code in jQuery at the end of the document:

<script>
     $("#right").css("height",$("#left").height());
</script>

The left one has some content (that gives it its height) that takes some time to load, so, with this code, when I load the page the one of the right has 0px of height, I think that that's because the left one hasn't loaded its content when the code runs. So, What should I do to make sure that I'm running the code when the left one has its content loaded? And, How can I make the code refresh every time the left's height changes?

Although that code doesn't work, I created a function (called equalize) with that code, and then I created a button with onclick="equalize()", and when I press the button, the right's height gets the left's height. .-.

Foi útil?

Solução 5

Ok, Thank you all for your answers, but if someone gets in this case here's how I solved it:

The #left 's height has a relation of the 50% of its width. So, because the width loads with the whole document, I put this js (With jQuery...):

$("#right").css("height",$("#left").width()/2);

And... that's it :)

Thanks to T J (Who made me realize it) and for all those who answered :D

Outras dicas

try this:

<script>
  $(document).ready(function(){
     $("#right").css("height",$("#left").height()+"px");
  });

</script>

Use jQuery's on method and wait for the load event to fire:

$(window).on('load', function(){
    $("#right").css("height", $("#left").height().toString() + "px");
});

The load event fires when its subset of resources (e.g., images) have all been loaded. By attaching it to the window, this will wait for all the pages resource's to be loaded before executing the function.

According to the info you shared in question, If you simply want two <div> to have the same height upon resizing the window, there is no need to use jQuery - simply specify equal height for both divs in % of the parent height.

<div id='container'>
    <div id='left'></div>
    <div id='right'></div>
</div>

css

*{
 margin:0;
 padding:0;
}
html, body{
 height:100%;
}
#container{
 height:100%;
}
#container div{
 display:inline-block;
}
#left{
 height:100%;
 width:200px;;
 background:dodgerblue;
}
#right{
 height:100%;
 width:50%;
 background:orange;
}

Something like this JSFiddle

Am i missing something? is there a reason to use jQuery? please comment below..

I suggest you to use these function to equalize two or more div's:

var maxHeight = 0;

$(".test").each(function(){
   if ($(this).height() > maxHeight) { maxHeight = $(this).height(); }
});

$(".test").height(maxHeight);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top