Notorious_Creed Notorious_Creed - 3 months ago 7
CSS Question

Prev and next buttons to change divs

I'm trying to create a code in jQuery that adds the class active to the next div and removes it from the previous div and vice versa with the previous. This all in mind with animations I want to add later.

If you want to see the code with HTML and CSS:
http://codepen.io/salman15/pen/kXVmRG?editors=1010

$(document).ready(function() {
$('#next').click(function() {
var location = $(this).parent().parent();
$('.active').removeClass('active');
$('div').next('#case').addClass('active');
});

$('#prev').click(function() {
var location = $(this).parent().parent();
$('.active').removeClass('active');
$(this).prev('#case').removeClass('active');
});
});

Answer

You should not give your div elements the same id value: that is invalid HTML. Instead use "case" as a class value.

To apply the active class you can just chain to the removeClass method, find the next div, and apply addClass to that element.

Here is a simplified snippet:

$(document).ready(function(){
  $('#next').click(function(){
    if ($('.active').next('.case').length) {
        $('.active').removeClass('active')
                    .next('.case')
                    .addClass('active');
    }
  });
  $('#prev').click(function(){
    if ($('.active').prev('.case').length) {
        $('.active').removeClass('active')
                    .prev('.case')
                    .addClass('active');
    }
  });
});
.active { background: yellow; border: 1px solid }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="next">
  <h1>next</h1>
</div>
<div id="prev">
  <h1>prev</h1>
</div>
<div class="case active">content 1</div>
<div class="case">content 2</div>
<div class="case">content 3</div>