Jalen Nguyen
Jalen Nguyen

Reputation: 21

jQuery Click Counter

I am trying to make a simple cookie clicker type game (click counter) with jQuery. I want to have a button that makes the value of clicks go up by one every second. How would I go about this and are there any errors in my coding? I'm very new to all of this.

Here's my code:

$(function() {
  $('#target').click(function() {
    $('#output').html(function(i, val) {
      return val * 1 + 1;
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
  <button id="target" type="button">Click</button>
  <div id="output">0</div>
</div>

Upvotes: 2

Views: 6659

Answers (2)

castletheperson
castletheperson

Reputation: 33496

A button that automatically "clicks" the button would require that you add a setInterval that refreshes the number continually, and another button that changes how many clicks get added with each refresh.

Here's how I would do it. I've coded it in such a way that you could easily add other buttons which change the click rate in other ways. Notice the difference between incrementing the count and incrementing the countRate. JSFiddle

$(function() {
  var count = 0, countRate = 0, output = $('#output');

  setInterval(function(){ output.html(count) }, 1); // update continually
  setInterval(function(){ count += countRate }, 1000); // update once-per-second

  $('#click').click(function(){ count += 1 });
  $('#autoClick').click(function(){ countRate += 1 });
});
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>

<button id="click">Click</button>
<button id="autoClick">Auto Click</button>
<div id="output">0</div>

Upvotes: 2

Erresen
Erresen

Reputation: 2043

If I'm understanding you correctly, the bit you're struggling with is increasing the value of each click, once per second. You'll want to use setInterval

jsfiddle Demo

var score = parseInt($('#output').html());
$(function() {
  setInterval(function() {
    score += 1;
    $('#output').html(score);
  }, 1000);

  $('#target').click(function() {
    score += 1;
    $('#output').html(score);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
  <button id="target" type="button">Target</button>
  <br/>
  <div id="output">0</div>
</div>

Upvotes: 0

Related Questions