Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number elements starting from the middle element in jQuery [closed]

I have an odd number of elements.

<div class="line"></div>
<div class="line"></div>
<div class="line"></div>
<div class="line"></div>
<div class="line"></div>

I wonder how to give them a numbered class in jQuery, count from the middle element, like this:

<div class="line no2"></div>
<div class="line no1"></div>
<div class="line no0"></div>
<div class="line no1"></div>
<div class="line no2"></div>

anyone?

Edit:

Before, I will check the amount of elements. If the amount is an even value I'm adding an additive element to have an odd number of elements.

I want to archieve a circle text shape, like this example (see curve). The number of lines is not really important, because the middle line <div class="line no0"></div> will be the vertical center of the circle.

like image 1000
Thomas Avatar asked Dec 16 '22 03:12

Thomas


1 Answers

Try this :

var middle=Math.ceil($("div").length/2);
var divs=$("div.line");
divs.each(function (){
    $(this).addClass('no'+Math.abs(middle-(divs.index($(this))+1)));
});

http://jsbin.com/IKiGexIr/5/edit

Shorter version : ( PSL )

var middle=Math.ceil($("div").length/2),divs=$("div.line");
    divs.addClass(function (i){ return 'no'+ Math.abs(middle-(i+1)); });

enter image description here

like image 169
Royi Namir Avatar answered Dec 28 '22 09:12

Royi Namir