Search code examples
javascripthtmljqueryjquery-selectorsjquery-traversing

jquery show only next div with same class


I'm trying to do a sequence of steps with jquery but I'm failing to achieve the result I want.

I have 3 steps, with a class of .wiki-step- plus a number. my javascript is this one:

function stepping() {
    var stepButton = $("a.button");
    var step = $("[class*='wiki-step-']");
    stepButton.closest(step).hide().next(step).show();
}

$("a.button").on("click",function(){
    stepping();
});

It works correctly with only 2 steps but I've noticed that if I add a third one, the jquery (next) shows all the other steps at once but I want to show only the next div in line, not all of them.

Here's a fiddle: https://jsfiddle.net/vsomcag2/1/ you can see how it shows the 2nd and 3rd step at once.

I can't use nextUntil() i guess, I think I should use a counter of some sort but I don't know where to start. I would like to avoid specifying numbers because I would like to have the ability to add or remove steps without editing the js.

Any help is greatly appreciated.

    function stepping() {
        var stepButton = $("a.button");
        var step = $("[class*='wiki-step-']");
        stepButton.closest(step).hide().next(step).show();
    }

    $("a.button").on("click",function(){
        stepping();
    });
div[class*="wiki-step-"] {
        display: none;
       width: 500px;
       height: 500px;
       border:1px solid red;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div class="wiki-step-1" style="display:block">
<h1>step 1</h1>
<a href="#" class="button">next</a>
</div>

<div class="wiki-step-2">
  <h1>step 2</h1>
<a href="#" class="button">next</a>
</div>

<div class="wiki-step-3">
  <h1>step 3</h1>
</div>


Solution

  • You need to get reference to the clicked object a and show hide according to that object.

    function stepping(obj) {
      var stepButton = $(obj);
      var step = $("[class*='wiki-step-']");
      stepButton.closest(step).hide().next(step).show();
    }
    
    $("a.button").on("click", function () {
       stepping(this);
    });
    

    Here is jsfiddle