rockey dsouza
rockey dsouza

Reputation: 84

Add Class for <LI> on prev and next click

How to add class for list li tag simultaneously when click on next and prev button.

on click of next and prev the active class should add and remove simultaneously for li.

Can anybody solve this issue.

Thanks in advance :)

$(document).ready(function() {
  $(".divs div").each(function(e) {
    if (e != 0)
      $(this).hide();

  });

  $("#next").click(function() {
    $(".list li").addClass("active");
    if ($(".divs div:visible").next().length != 0)
      $(".divs div:visible").next().show().prev().hide();
    else {
      $(".divs div:visible").hide();
      $(".divs div:first").show();
    }
    return false;
  });

  $("#prev").click(function() {

    if ($(".divs div:visible").prev().length != 0)
      $(".divs div:visible").prev().show().next().hide();
    else {
      $(".divs div:visible").hide();
      $(".divs div:last").show();
    }
    return false;
  });
});
.active {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="divs">
  <div class="cls1">1</div>
  <div class="cls2">2</div>
  <div class="cls3">3</div>
  <div class="cls4">4</div>
  <div class="cls5">5</div>
  <div class="cls6">6</div>
  <div class="cls7">7</div>
</div>
<ul class="list">
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
</ul>

<a id="next">next</a>
<a id="prev">prev</a>

Upvotes: 2

Views: 2112

Answers (3)

1990rk4
1990rk4

Reputation: 768

You can try with following methods:

.next().addClass('your-class') and .prev().addClass('your-class')

Hope it may help you....

Upvotes: 0

RaJesh RiJo
RaJesh RiJo

Reputation: 4400

Take a look at this JsFiddle

What you are suppose to do is, you are suppose to add same class names for the corresponding li. On next() or previous() click, get the visible div's class and make use of it to set active on the list li.

Hope it helps.

Upvotes: 3

Vahid Boreiri
Vahid Boreiri

Reputation: 3438

The active class will apply to <li> tags if you press the next button now. And if you want that the perv button do the same should change your code into this:

$("#prev").click(function(){
   $(".list li").addClass("active");
        if ($(".divs div:visible").prev().length != 0)
            $(".divs div:visible").prev().show().next().hide();
        else {
            $(".divs div:visible").hide();
            $(".divs div:last").show();
        }
        return false;
    });

If I got your mean correctly, it should work.

Upvotes: 0

Related Questions