Ωmega
Ωmega

Reputation: 43673

Incorrect jQuery element width calculation

Having a simple html code

<div id="header">
  <div id="headerBox">
    <div id="headerText">
    </div>
  </div>
</div>

with css styles

div#header {
    display: block;
    overflow: hidden;    
    margin: 0;
    padding: 0;
    width: 100%;
}
div#headerBox {
    padding: 1em;
    text-align: center;
    white-space: nowrap;
    border-bottom: 10px double gray;
}
div#headerText {
    background: red;
    display: inline-block;
}

and jQuery (2.x edge)

function resize(win) {
  var size;
  var w = $('#headerBox').width();
  $('#headerText').html('');
  $('#headerBox').css('font-size', 1 + 'px');
  $('#headerText').html(
    "width of <span style=\"font-size:2em;\">headerBox</span> element is " + w + "px");
  while ($('#headerText').width() <= w) {
    size = parseInt($('#headerBox').css('font-size').replace(/\D+$/, ''), 10);
    $('#headerBox').css('font-size', (size + 1) + 'px');
  }
  $('#headerBox').css('font-size', size + 'px');
}

$(window).resize(function(e){
  resize(this)
});

resize(window);

all together accessible via this fiddle,

I experience incorrect jQuery element width calculation. When you access the above fiddle, you see that headerText element is too wide. There should be same right padding as is on left side, text should be centered. Once you resize the Result window (in the fiddle), text is adjusted as supposed to.

Question is WHY there is incorrect calculation on the very first time?

It seems that var w = $('#headerBox').width(); is incorrect calculated. WHY?


enter image description here

Upvotes: 0

Views: 3943

Answers (2)

Ωmega
Ωmega

Reputation: 43673

Found the problem:

Due to padding: 1em; for headerBox, width of this element changes with change of font-size.

So in while loop I need to work with up-to-date information, not the one I stored at the beginning.

Therefore

var w = $('#headerBox').width();
...
while ($('#headerText').width() <= w) {
  ...
}

needs to be changed to

while ($('#headerText').width() <= $('#headerBox').width()) {
  ...
}

Upvotes: 1

CosX
CosX

Reputation: 2030

JQuery .width doesn't include the padding of #headerbox. Use .outerWidth to get correct width.

var w = $('#headerBox').outerWidth();

Upvotes: 0

Related Questions