Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible, to add auto incremental classes to a list by using jquery or javascript

is it possible, to add auto incremental classes to a list

<ul id="list">
 <li>Element 1</li>
 <li>Element 2</li>
 <li>Element 3</li>
 <li>Element 4</li>
 <li>Element 5</li>
</ul>

Now, If I hover on Element 3 then, add auto incremental classes to li like example below...

<ul id="list">
 <li class="left2">Element 1</li>
 <li class="left1">Element 2</li>
 <li>Element 3</li>
 <li class="right1">Element 4</li>
 <li class="right2">Element 5</li>
</ul>

Again if hover on Element 1 then, add auto incremental classes to li like example below...

<ul id="list">
 <li>Element 1</li>
 <li class="right1">Element 2</li>
 <li class="right2">Element 3</li>
 <li class="right3">Element 4</li>
 <li class="right4">Element 5</li>
</ul>

sorry about my poor English. Thank you.

like image 833
M.Kaisar Avatar asked Dec 24 '22 05:12

M.Kaisar


2 Answers

$('li').hover(function() {
$('li').removeClass();
  var next = $(this).nextAll();
  next.each(function(i, v) {
    $(this).addClass('right' + (i+1))

  })

  var prev = $(this).prevAll();
  prev.each(function(i, v) {
    $(this).addClass('left' + (i+1))

  })

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="list">
  <li>Element 1</li>
  <li>Element 2</li>
  <li>Element 3</li>
  <li>Element 4</li>
  <li>Element 5</li>
</ul>

Use .prevAll() and .nextAll()

Description: Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector.

Description: Get all following siblings of each element in the set of matched elements, optionally filtered by a selector.

then iterate on the li and assign the index. make sure to remove the li classes so it wont stack up

like image 87
guradio Avatar answered Dec 26 '22 20:12

guradio


Based on example, I cleared all the class in <li> when mouseenter anyone of the <li> and add new class for them.

left1+n will add to previous all <li> and right1+n will add to next all <li>

$("#list > li").on("mouseenter", function(){
    $("#list > li").attr("class", "");

  $(this).prevAll("li").each(function(i) {
    $(this).addClass('left' + (i+1));
  });
  $(this).nextAll("li").each(function(i) {
    $(this).addClass('right' + (i+1));
  });
});
like image 23
J.C. Fong Avatar answered Dec 26 '22 18:12

J.C. Fong