Zsolt Janes Zsolt Janes - 9 months ago 46
Javascript Question

Button onclicked class changed but only the first click working

I would like to be set class

start1
from
start0
after clicking on Start button. After that I would like to change
start1
to
start2
after clicking on Start again and so on. Can you tell me what is the problem only the first click is working.



$(".start0").on("click", function () {
$(".start0").attr("class", "btn btn-success start1");
});
$(".start1").on("click", function () {
$(".start1").attr("class", "btn btn-success start2");
});
$(".start2").on("click", function () {
$(".start2").attr("class", "btn btn-success start3");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="btn btn-success start0">Start</button>




Answer Source

When you use things like .click() or .on(), you're binding the click events to elements that satisfy the selector. "Find this element, give it this event".

But you're doing...

 $(".start1").on("click", function () {
        $(".start1").attr("class", "btn btn-success start2");
  });

...before .start1 exists, and so on.

This is obfuscated and I suggest doing this differently, but in an effort to push you in the right direction, here would be your code reformatted to satisfy your intent:

$(".start0").on("click", function () {
    $(".start0").attr("class", "btn btn-success start1");
    $(".start1").on("click", function () {
        $(".start1").attr("class", "btn btn-success start2");
        $(".start2").on("click", function () {
            $(".start2").attr("class", "btn btn-success start3");
        });
    });
});

Personally, I might do something like this...

var i = 0;
$('.btn-success').click(function() {
   $(this).removeClass('start'+i);
   i++;
   $(this).addClass('start'+i);
});

JSFiddle