0

How do I set width and height of a DIV based on another div?

This is how I've done it but it works only when the alert is present??

var readyC = setInterval(function() {
  if (Condition) {
    $('#divAA').width($('#divBB').width()).height($('#divBB').height()); 
          //alert($('#divBB').width())  // works when this is uncommented?? 
  }
  clearInterval(readyC);
}, 10);

EDIT:

Fixed typo:

$('#divBB'+i) to $('#divBB')

Fergoso
  • 1,584
  • 3
  • 21
  • 44

2 Answers2

0

If the content of your divs are loaded dynamically, then you will need to use window.load event to get its correct height as discussed here: https://stackoverflow.com/a/13071846/1845408

$(window).load(function() {
    $('#divAA').width($('#divBB').width()).height($('#divBB').height()); 
});
Community
  • 1
  • 1
renakre
  • 8,001
  • 5
  • 46
  • 99
0

The reason why you're getting it only when you keep an alert is, you're using setInterval with such small interval of 10ms.

When you use alert, the execution is stopped and that's why you see the div resized. You must increase the interval to a higher value.

Also clearInterval is not inside else block, So it means what the timer will clear on first attempt itself. In that case you don't need a setInterval at all.

Update based on comments

As you're looping through a list of divs to update the height of other divs, you must use self invoking function to bind the value of i correctly.

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
mohamedrias
  • 18,326
  • 2
  • 38
  • 47