Zsolt Janes
Zsolt Janes

Reputation: 840

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>

Upvotes: 1

Views: 73

Answers (2)

Townim Faisal
Townim Faisal

Reputation: 325

Event handlers attached using the on() method will work for both current and future elements (like a new element created by a script). But your future elements .start1 etc. are not binded. so do this and you can understand by watching in console.

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

Upvotes: 1

Tyler Roper
Tyler Roper

Reputation: 21672

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

Upvotes: 1

Related Questions