Jop
Jop

Reputation: 90

Making a number increment when a class is clicked

So right now I have this code:

 var s = 0;

 $('.inner').click(function () {
    $(this).addClass("selected");
    $(this).removeClass("inner");
    s++;
    $('#sslots').replaceWith(s);
 };

But for some reason, the javascript wont update, it will start out as blank (not zero) and then change to 1 once I click one of the div's with "inner" as the class but then won't do anything after that..

Upvotes: 0

Views: 44

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

The problem is after your first click the element sslots does not exists because you are replacing it with the number, instead you have to change the content of sslots - you can use .text() for that

var s = 0;

$('.inner').one('click', function() {
  $(this).addClass("selected");
  $(this).removeClass("inner");
  s++;
  $('#sslots').text(s);
});
.inner {
  color: green;
}
.selected {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="sslots">0</div>
<div class="inner">inner</div>
<div class="inner">inner</div>
<div class="inner">inner</div>
<div class="inner">inner</div>
<div class="inner">inner</div>

Also from the code it looks like you want to execute the click once per inner element(ie if you click multiple times in an element only first one should count), in that cause use .one() to register a handler which will be executed only once

Upvotes: 2

Related Questions