0

We all know that jQuery doesn't calculate the width of hidden elements. Right? Has this changed in jQuery 1.10?

In this jsFiddle, the width of the hidden LI <li style="display:none;">a hidden li</li> is calculated. Why is this?

And if a recent update changed the behavior, how can I make sure that width ISN'T calculate? I tried:

$('#theList li').each(function() {
    totalWidth += $(this).is(':visible').width();
});

But that didn't work either - it still returned the element and its width.

Community
  • 1
  • 1
dmathisen
  • 2,269
  • 3
  • 36
  • 63

1 Answers1

1

You may want to check first if the elements are visible and then perform your function.

var totalWidth = 0;

$('#theList li').each(function() {
    if ($(this).is(":visible")){ // CHECK FIRST IF VISIBLE
    var $this = $(this);
    totalWidth += $this.width();

    $('#theListItems').append($this.text() + " ("  +$this.width() + " width)<br>");
    $('#totalWidth').html(totalWidth);
    }
});

Jsfiddle: http://jsfiddle.net/javascript/LQZB2/

jQuerybeast
  • 14,130
  • 38
  • 118
  • 196
  • Thanks. That works perfectly. I wonder when the calculation changed. I don't see any mention of it or notes on the jQuery site, including on the .width() documentation page. – dmathisen Jul 15 '13 at 21:30
  • I've never read any of their documentations. It's pretty much common sense of sane design. In your case, you just check for each li, if visible. There's no other explanation to it. Feel free to check this as answered question. – jQuerybeast Jul 16 '13 at 10:54
  • "It's pretty much common sense" Yeah, agreed - but that's not how it used to be. jQuery used to ignore any hidden elements. Anyway, marked it as answered. – dmathisen Jul 16 '13 at 13:38
  • 1
    What I meant is that jQuery has a poor documentation. The did, however, spent a massive amount of effort to update it from what it previously was but it still lacks some more complicated or specific examples like this one. – jQuerybeast Jul 16 '13 at 20:42