You can see the problem on http://jsfiddle.net/6gnAF/1/
I’ve little problem with my list elements.
I’m using very simple unordered list like;
<div>
<ul>
<li class='button'>Element 1</li>
...
<li class='button'>Element N</li>
</ul>
</div>
(Number of list elements, N, varies on every page.)
The div which contains the ul is 696 px width. List elements, li, are horizontally aligned, and when they reach end of div’s width, they contiues on new line.
What I wanted to adding class .left the first li of every line, and class .right to the last one.
$('li').each(function() {
var liWidthOut = $(this).width();
totalWidth += liWidthOut;
if (totalWidth >= divWidth) {
$(this).addClass("left");
$(this).prev().removeClass("middle").addClass("right");
totalWidth = liWidthOut;
}
else {
$(this).addClass("middle");
}
});
I managed that with Jquery, but I’ve a little problem.
You can see the problem on http://jsfiddle.net/6gnAF/1/
The problem is, .left and .right classes change the width of li elements which are added to, so some times they create new lines, and last li elements become first one which have .right class, instead of .left.
How can I fix this?
(Sorry for the grammatically errors)
Your code is mostly right, just two nitpicks which made it go wrong:
Use
var liWidthOut = this.offsetWidth;instead ofvar liWidthOut =as the later is giving you the width of the inner$(this).width();
text, instead of also adding the padding, as
offsetWidthdoes.Apply the
.buttonclass before starting looping and calculatingwidths, as the
.buttonstyle will affect the elements width, you have toapply it in the first place so your calculations don’t fail later.
See working demo of your code with those two things corrected.