umbriel
umbriel

Reputation: 751

Get (calculate) total width of mutiple elements with dynamic widths

Hello I'm going to be as pedagogic as possible!

So I have a list of li's wrapped within a ul.

<ul class="ulclass">
   <li class="liclass">
       <div class="button">expand</div>
       <img src="600px_wide.jpg"/>
   </li>
   <li class="liclass">
       <div class="button">expand</div>
       <img src="800px_wide.jpg"/>
   </li>
   <li class="liclass">
       <div class="button">expand</div>
       <img src="300px_wide.jpg"/>
   </li>
</ul>

within each li element there is a button, when clicked the li will expand to the width of the nested image. So if the image is 800px wide the li will expand accordingly.

Now the situation is that I want to calculate the total width of all the li's dynamically. Right now I'm using something like:

$(li).each(function() {
totalWidth += parseInt($(this).width());
});

which will get the width of all the li's on page load. But after expanding say one li the width value doesn't change. I want the total width to change when I expand/contract the li's A event listener maybe? I'm really new when it comes to callbacks and such. So I would like some guidance at least. Maybe it's not even possible...

I Appreciate all help! Thanks

Upvotes: 1

Views: 1334

Answers (2)

Jeff
Jeff

Reputation: 12795

James' answer is good, but Depending on how often/how many places the value is read, you might prefer to call that code whenever the value is asked for. So instead of someDependentFunction(totalWidth), you would have someDependentFunction(totalWidth()), where totalWidth is:

function totalWidth = new function() {
    var total = 0;
    $(li).each(function() {
        total += parseInt($(this).width());
    });
    return total;
}

As James said, if you're worried about the performance of calling $(li), then if it's anything like the YUI equivalent it will cache the results after the first call so it really shouldn't be much at all. I'm not really a jQuery pro though, so that might not be the case.

Upvotes: 1

James Montagne
James Montagne

Reputation: 78740

You could simply call this code which calculates the width each time that you expand or contract an li. Unless you have a huge number of li elements, the performance of just adding them all back up again shouldn't be too bad.

Upvotes: 0

Related Questions