Praveen
Praveen

Reputation: 1802

add class to all elements one by one on click

I just want to move class on every click from first to last element. On my first click it adds the class to first <li> and on second click it moves the class to second <li> and remove the class from first one and so on.

<script>
    $(function() {
        $('button').on('click', changeClass);

        function changeClass() {
            var ind = $(this).index();
            var i = 0;
            $("li").eq(i).addClass("current").siblings().removeClass("current");
        }
    });
</script>

http://codepen.io/anon/pen/QNyWQL

Upvotes: 4

Views: 2237

Answers (3)

Gurpreet Singh
Gurpreet Singh

Reputation: 400

First of all find the next li with class 'current' as well as remove the class of current li. Then check if length is >0 means element exists otherwise not.

$('button').on('click', function() {
   var next = $('#main').find('li.current').removeClass('current').next('li');
   if(next.length) { next.addClass('current'); }
   else { $('#main').find('li').first().addClass('current'); }
});

<ul id="main">
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li> 
  <li>Five</li>
</ul>

https://jsfiddle.net/sbLhewgh/

Upvotes: 0

Ibrahim Khan
Ibrahim Khan

Reputation: 20740

You can do it like following using eq() method. First set index to 0 and get the total number of li and on click of the button remove current class from all li and set current class to the li at index. After that increase the index by 1. To get back the first li after reaching last use (index+1) % total.

var index = 0;
var total = $("li").length;

$("button").click(function() {
  $("li").removeClass("current");
  $("li").eq(index).addClass("current"); 
  index = (index+1) % total;
});
.current{color:red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
    <li>one</li>
    <li>one</li>
    <li>one</li>
    <li>one</li>
    <li>one</li>
</ul>

<button>click</button>

Upvotes: 2

Anubhab
Anubhab

Reputation: 741

Another approach without index.

$("button").click(function(){
  var el = $('li.current');

  if(el.length == 0){
     $('ul').find('li').eq(0).addClass('current');//if no current exist
     return;
  }
  $('li.current').removeClass('current');
  if(typeof el.next() !== 'undefined'){
      el.next().addClass('current');
  }
})
.current{color:red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
    <li>one</li> <!-- initialize with atleast one class current -->
    <li>one</li>
    <li>one</li>
    <li>one</li>
    <li>one</li>
</ul>

<button>click</button>

Upvotes: 0

Related Questions