0

I saw this question today and curiously made my own concept(or may be as of the OP concept of that question) but stucked here that how can I iterate over the list after the active class and start again from beginning. Let's make me clear from the following html:

<ul>
  <li name="6">one</li>
  <li name="1" class="active">two</li>
  <li name="2">three</li>
  <li name="3">four</li>
  <li name="4">five</li>
  <li name="5">six</li>
</ul>

Now, if the active class is in second last li, then look like this:

<ul>
  <li name="3">one</li>
  <li name="4">two</li>
  <li name="5">three</li>
  <li name="6">four</li>
  <li name="1" class="active">five</li>
  <li name="2">six</li>
</ul>

For longer list this would look like this:

<ul>
  <li name="3">one</li>
  <li name="4">two</li>
  <li name="5">three</li>
  <li name="6">four</li>
  <li name="1" class="active">five</li>
  <li name="2">six</li>
  <li name="3">seven</li>
  <li name="4">eight</li>
  <li name="5">nine</li>
  <li name="6">ten</li>
  <li name="1">eleven</li>
  <li name="2">tweleve</li>
</ul>

I mean I wanted to do like this:

  • From active class it should start from 1 and increase by 1 for next sibling
  • From active class it should start from 1 and decrease by 1 for previous sibling (meaning that 6, 5, 4...)

What I've done is:

$('li').attr('name',function(i){
  i += 5
    return i % 6 + 1;
});

But it will just results fine if the active class is in second list. So how should I do if I don't know where the active class would be?

Community
  • 1
  • 1
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231

2 Answers2

2

here's a good way to do it... ;)

var stopvalue = 6;
var activeindex = $('li.active').index() % stopvalue ;
$('ul>li').attr('name', function (i) {
    return (i + (stopvalue - activeindex)) % stopvalue  + 1;
});

demo

Reigel Gallarde
  • 64,198
  • 21
  • 121
  • 139
  • @C-link, I'm sorry but I don't know how to explain it... What I did was look for the relationship of the needed output number and the given numbers. I come up with that. It took me time, but it works. – Reigel Gallarde Jun 05 '14 at 15:59
0

Check this Demo Fiddle , using .nextAll() and .prevAll()

var activeVal = $( "li.active" ).attr('name');

$( "li.active" ).nextAll().each(function(i){
        $(this).attr('name',function(){
        return i + parseInt(activeVal) + 1;
    });    
}).end().prevAll().each(function(i){
    $(this).attr('name',function(){
        return i +parseInt(activeVal)+1;
    });    
});

Comments:

  • First Loop - .nextAll(). Iterate form next till last element.
  • Second Loop - .prevAll(). Iterate from previous to the first.

To check the iterations verify this in console :

$('li').each(function(){
   console.log($(this).attr('name')); 
});

Shaunak D
  • 20,588
  • 10
  • 46
  • 79