Alessandro
Alessandro

Reputation: 3761

Set and retrieve width using JQuery

I have a problem using JQuery. I am writing a function that dynamically resizes an absolute positioned 'ul' width according to the previous sibling's width (which is an 'h4'). The code is:

$(this).children('h4').each(function (i) {
   var beforeWidth = $(this).width(); // This reads for example 234
   $(this).next().width($(this).width()); // This should set the width
   var afterWidth = $(this).next().get(0).clientWidth; // This returns always 0
});

HTML is like that:

<div style="width: 30%;">
   <h4>title</h4>
   <ul style="position: absolute;">
      <li>item 1</li>
      <li>item 2</li>
   </ul>
</div>

I can't understand why it returns 0, so my 'ul' is always smaller than the corresponding 'h4'. I have to say that 'h4' width is set in CSS using a percentage value.

EDIT: I should have said that this happens only if that piece of code is inside a hidden div (that I use as a modal popup). Otherwise it works as expected!

Thank you guys!

Upvotes: 0

Views: 128

Answers (1)

Teun Pronk
Teun Pronk

Reputation: 1399

change

var afterWidth = $(this).next().get(0).clientWidth;

To

var afterWidth = $(this).next().width();

And it should work

Upvotes: 1

Related Questions