Show steps one at a time

I run a tutorial website that has a jQuery script to show instructions one at a time, by clicking the 'Next Step' button. When there are no more steps, the code hides the 'Next Step' button and shows the 'Next Tutorial' button. Here is the code for this...

var stepNumber = 1;
$(function() {
  $('p.step:nth-child(' + stepNumber + ')').show();
  $('#nextstep').click(function() {
    $('p.step:nth-child(' + stepNumber+++')').show();
    $('p.step:nth-child(' + stepNumber + ')').fadeIn();
    if (stepNumber == $('p.step').length) {
      $('#nextstep').hide();
      $('#nexttut').show();
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="pad">
  <p class="step">
    1
  </p>
  <p class="step">
    2
  </p>
  <p class="step">
    3
  </p>
  <p class="step">
    4
  </p>
  <p class="step">
    5
  </p>
  <p id="nextstep"><a href="#!" role="button" class="btn btn-primary" title="Next Step">Next Step</a>
  </p>
  <p id="nexttut"><a href="#!" role="button" class="btn btn-primary" title="Next Tutorial">Next Tutorial</a>
  </p>
</div>

This script can be used on any number of steps, without changing any of the jQuery.

My problem is that it has no function whatsoever. I am fairly new to jQuery and I can't spot anything wrong. Can you?

Here is a fiddle

Answers 1

  • You have to hide all .step initially. Use following CSS to do that.

    .step{
        display: none;
    } 
    

    Full Code

    var stepNumber = 1;
    
    $('p.step:nth-child(' + stepNumber + ')').show();
    $('#nextstep').click(function() {
      $('p.step:nth-child(' + stepNumber++ + ')').show();
      $('p.step:nth-child(' + stepNumber + ')').fadeIn();
      if (stepNumber == $('p.step').length) {
        $('#nextstep').hide();
        $('#nexttut').show();
      }
    });
    .step{
      display: none;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="pad">
      <p class="step">
        1
      </p>
      <p class="step">
        2
      </p>
      <p class="step">
        3
      </p>
      <p class="step">
        4
      </p>
      <p class="step">
        5
      </p>
      <p id="nextstep"><a href="#!" role="button" class="btn btn-primary" title="Next Step">Next Step</a></p>
      <p id="nexttut"><a href="#!" role="button" class="btn btn-primary" title="Next Tutorial">Next Tutorial</a></p>
    </div>


Related Articles