Search code examples
javascriptjquerycsspaginationshow-hide

Simple Next and Previous Show and Hide with jQuery


I'm trying to figure out the simplest way to show and hide a series of divs with Previous and Next buttons by adding and removing some classes.

So far, I can get the Next button to trigger, but it's adding the active class to all of the divs and not just the next one in line.

I've been reading through other examples and so far they seem really bloated or not what I am looking for specifically.

Here's what I have so far:

Codepen Link: https://codepen.io/ultraloveninja/pen/pxrrmy/

HTML:

<div class="group">
  <div class="item active">
    <h2>Thing One</h2>
  </div>
  <div class="item">
    <h2>Thing Two</h2>
  </div>
  <div class="item">
    <h2>Thing Three</h2>
  </div>
</div>
<div class="btns">
  <a href="#" class="btn prev">Previous</a>
  <a class="btn next" href="#">Next</a>
</div>

JS:

$('.next').on("click", function(){
  if($('.item').hasClass('active')) {
    $('.item').next().addClass('active');

  }
})

CSS:

body {
  padding: 10px;
}
.active {
  display:block !important;
}

.item {
  display:none;
}

It seems like this should be fairly simple, but I can't seem to think of how to target the next div by itself without it showing all of the other ones.


Solution

  • Basically you should get your last active element and activate next after it:

    $('.next').on("click", function(){
      const $active = $('.item.active');
      const $next = $active.next();
    
      if ($next.length) {
        $active.removeClass('active');
        $next.addClass('active');
      }
    })
    

    The problem in your current code is that you are getting all items and performing hasClass on all of them so it returns true all the time because there is at least one element with this class and then you are getting next element after each item element and add active class to them so all of your elements are activated in result.