this is slightly related to this question Invoking a jQuery function after .each() has completed
But the solution doesn't quite seem to work for me.
Basically I have piece of JavaScript that calculates the width of some elements:
var totalWidth = 0;
$element.find('li').each(function () {
totalWidth += $(this).width();
});
After this I want to then use the width to set another element:
$element.width(totalWidth);
If I attach the debugger it works but if I just run it it doesn't. Which makes me think that the width is being set before the .each()
completes.
I tried using .promise()
to fix this issue but it doesn't appear to make a difference.
var totalWidth = 0;
$element.find('li').each(function () {
totalWidth += $(this).width();
});
$element.promise().done(function () {
$element.width(totalWidth);
});
Here's my HTML
<div class="carousel">
<ul>
<li>
<img src="/Images/Travel2New/Adverts/advertHolder_1.png" />
</li>
<li>
<img src="/Images/Travel2New/Adverts/advertHolder_2.png" />
</li>
<li>
<img src="/Images/Travel2New/Adverts/advertHolder_3.png" />
</li>
<li>
<img src="/Images/Travel2New/Adverts/advertHolder_4.png" />
</li>
<li>
<img src="/Images/Travel2New/Adverts/advertHolder_5.png" />
</li>
</ul>
</div>
Any ideas?