Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get li width + margin using jquery

my code is something like this

//css
li{display:inline-block}

//html #li margin and width are dynamic
<ul>
<li style='margin:30px;width:100px;'>Pic</li>
<li style='margin:40px;width:200px;'>Pic</li>
<li style='margin:10px;width:500px;'>Pic</li>
<li style='margin:50px;width:300px;'>Pic</li>
</ul>

how to make a jquery function that will take an li index as an input and it will return the width of all li from the beginning to that index + margins ' left + right '

Examples // something like this   
myFunction(1); //output 440 (( 30 margin-left [0] + 30 margin-right [0] + 40 margin-left [1] + 40 margin-right [1] + 100 width [0] + 200 width [1] )) 

myFunction(2); //output 960 (( 30 margin-left [0] + 30 margin-right [0] + 40 margin-left [1] + 40 margin-right [1] + 10 margin-left [2] + 10 margin-right [2] + 100 width [0] + 200 width [1] + 500 width [2] )) 
like image 271
trrrrrrm Avatar asked Mar 09 '10 07:03

trrrrrrm


2 Answers

You're looking for outerWidth(true)

for example

$('li:eq(0)').outerWidth(true)

if you dont want the margin, but only want the padding and border, just do outerWidth()

So you can just add up the li's outerWidth's normally to get the sum of them all.

like image 138
Alex Sexton Avatar answered Oct 05 '22 11:10

Alex Sexton


$.fn.sumOuterWidth = function(useMargins) {
  var sum = 0;
  this.each(function() { 
    sum += $(this).outerWidth(useMargins);
  });
  return sum;
};

// example sum the width of the first 2 li's:
$('ul li').slice(0,2).sumOuterWidth(true) 

// Also gets the sum of the width of the first 2 li's:
$('ul li:eq(1)').prevAll().andSelf().sumOuterWidth(true);
like image 22
gnarf Avatar answered Oct 05 '22 11:10

gnarf