4

I am trying to make some tweaks to the jQuery UI MultiSelect Widget.

One issue I'm having is that the main control is a little too wide after I refresh the control. Looking at the code, the width is set using:

var width = this.element.outerWidth();

Where this.element refers to my original <select> control, which has been hidden by the jQuery UI MultiSelect Widget.

Playing around with this, I can see that outerWidth() returns 424 when my <select> element is hidden, and it returns 406 when it is visible. (Note that width() also returns a larger value when the element is hidden.)

Does anyone know why or how the width would change depending on whether or not the control is visible? The value returned when the control is visible appears to be the correct value.

EDIT:

I have created a jsFiddle to demonstrate this.

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
  • Do you have an `option` in your `select` that is wider than the `select` itself? – Arbel Jul 22 '15 at 17:19
  • @Arbel: No, the widest option is significantly narrower than the ` – Jonathan Wood Jul 22 '15 at 17:21
  • I recently answered a similar question. Basically the width functions are not guaranteed to return accurate widths when the element is hidden. You could rely on the reading that you get when the element is visible. – Salman A Jul 22 '15 at 17:56
  • 2
    http://api.jquery.com/outerwidth/ -> _The value reported by .outerWidth() is not guaranteed to be accurate when the element or its parent is hidden._ – Salman A Jul 22 '15 at 18:00
  • @SalmanA: I find this kind of strange. I read that it can return 0 for hidden elements, and I can't understand where the numbers it's returning for me are coming from. At any rate, if you want to move your replies to an answer, I can mark them as the right answer. – Jonathan Wood Jul 22 '15 at 18:16
  • Going off of @SalmanA's post, why don't you then show the element, get its width and then hide it? `this.element.show().outerWidth();` then `this.element.hide();` or something similar. P.S. I am not sure if this will work or not but it's worth a try. Otherwise break it up. – ctwheels Jul 22 '15 at 18:47
  • This is funny, and weird. I don't know if it is a bug or not or if it should behave like this but if you set `position:relative` on the parent element you get the same width. – xpy Jul 23 '15 at 07:57

1 Answers1

0

You can't get the width of a display:none; element.

You need to hide it with Position:absolute; and left:-999999px;.

Here the css you need. Don't forget to put position:relative on the div wrapper.

JsFiddle : http://jsfiddle.net/7xqk01oa/3/

Beauceron
  • 624
  • 5
  • 14