Sandra Willford Sandra Willford - 3 years ago 118
CSS Question

Jquery/JS Progress bars change class on button click

I am trying to make a simple progress bar where the click event changes the class according to my CSS classes:

.progress-bar {
&.step-1 {
width: 25%;
}
&.step-2 {
width: 50%;
}
&.step-3 {
width: 75%;
}
&.step-4 {
width: 100%;
}
}


so what i need to do is determine what the current class is and change the last character of the class so if the current bar is:

<div class="progress">
<div class="progress-bar progress-bar-striped step-1 active">Start</div>
</div>


and the user clicks on the next button:

<button class="btn btn-default progress-next">Next</button>


the script would be?

$(document).on('click', '.progress-next', function() {
//1. get current step-?
//2. incriment current step + 1
//3. remove current step-? from .progress-bar (once i know how to handle getting the classes i have this part :)
//4. add new incremented class to .progress-bar (once i know how to handle getting the classes i have this part :)
})

Answer Source

Try this, it should be what you are looking for.

I left your steps so you can follow the code and what it does.

$(document).on('click', '.progress-next', function() {
  //1. get current step-?
  
  var cl = $(".progress-bar").attr("class").split(/\s/).filter(function( cn ) {
        return cn.indexOf('step') === 0;
    });
  //console.log(cl)
  
  //2. incriment current step + 1
  var step = parseInt(cl[0].split('-')[1]) + 1;
  //console.log(step)
  
  //3. remove current step-? from .progress-bar (once i know how to handle getting the classes i have this part :) 
  var newclass = "step-" + step;
  //console.log(newclass)
  
  //4. add new incremented class to .progress-bar (once i know how to handle getting the classes i have this part :) 
  $(".progress-bar").removeClass(cl[0]).addClass(newclass)
  
})
.progress-bar {
  background-color: blue;
}

.progress-bar.step-1 {
  width: 25%;
}

.progress-bar.step-2 {
  width: 50%;
}

.progress-bar.step-3 {
  width: 75%;
}

.progress-bar.step-4 {
  width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="progress">
  <div class="progress-bar progress-bar-striped step-1 active">Start</div>
</div>

<button class="btn btn-default progress-next">Next</button>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download