jQuery .width() may not return pixels if element is hidden

jQuery 1.7.1

This got me for a while – while there is some discussion of .width() not behaving properly, only this stackOverflow [new window] hinted at the fact I wasn’t mad – all the others being sparse on examples, or poorly worded, leaving me wondering.

But, hell, I’ll give it a go, I thought, and it turned out that I was suffering exactly this:

The jQuery documentation clearly states:

The difference between .css(width) and .width() is that the latter returns a unit-less pixel value (for example, 400) while the former returns a value with units intact (for example,400px). The .width() method is recommended when an element’s width needs to be used in a mathematical calculation.

Ok, fair enough.

But I had {n} columns in a graph, containing a bar in each. The columns are set to (100 / {n})% width while the graph is being populated – and most importantly here, hidden.

I wanted to give my bars a little padding in pixels, so I needed to get the column size in pixels. In my example I had 4 columns, width 25% each, which worked out as 88px. Calling $(‘.column).width() -6 I expected to get 82, but got 19 instead.

One stackOverflow suggested that you should use an id instead – not ideal, as I don’t always know what the ids will be and don’t want to bother storing one just for the sake of the calculation. But I tried it with this case as I did know the ids – and it still didn’t work.

So I moved the column .width() call to after my .show() call – and magically, it returned 82.

Call it an ‘undocumented feature’, call it a bug, but watch out for it!

I ought to report this, but as of writing the jQuery trac is down. MySQL has gone away apparently :'(

Leave a Reply

Your email address will not be published. Required fields are marked *