Daniel Arant Daniel Arant - 1 year ago 138
Javascript Question

jQuery width, outerWidth(), innerWidth() returning incorrect data

For some reason, I cannot get jQuery to give me reliable width data for various elements. Here is a link to a fiddle that demonstrates the problem:

I am attempting to create a multidimensional drop down menu. As you can see in the jsfiddle, the second nested menu is not positioned correctly. The jQuery that I employ to position it queries the sibling anchor element using

to discover its width, then sest the left position of the nested list according to the returned width. When I give the sibling anchor element a set width in CSS then I get something near the correct value, but without that static width,
returns "2."

But even when I give anchor elements a set width,
still does not correctly incorporate the border of the element.

I'm about to pull my hair out. Why can't crap like this just work as advertised?

Answer Source

The various width commands don't work for hidden elements (display: none).

If you use css to set a width, jquery will return that. Otherwise you'll get no, or meaningless, results.

The classic solution is to position the element off the screen, check the width, then hide it and put it back. (You can probably find a jquery plugin that will do that in one command.)

Sometimes there are ways of restructuring the html and/or css so you avoid this.

Sometimes you can fix the size right after showing the element.

You can also try setting the visibility to hidden, so the element gets a size, but is invisible. Depending on the your design this might work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download