Button to increment or decrement at random

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
Marius
Posts: 107

Button to increment or decrement at random

Quick question:
How can I set a button that can increment and/or decrement at random a number as it is clicked?
This is the code i have.

Code: Select all

<button id='tst_btn'>Change counter</button>
<h3 id='tst_count'>0</h3>

<script>
var counter = 0,
  tst_count = document.getElementById('tst_count'),
  tst_btn = document.getElementById('tst_btn');

tst_btn.addEventListener('click', ()=>{
  //..code to increment or decrement at random ??

  tst_count.innerText = counter;
});
</script>

MarPlo Posts: 186
You can use Math.random() to decide whether you are going to increment or not:

Code: Select all

<button id='tst_btn'>Change counter</button>
<h3 id='tst_count'>0</h3>

<script>
var counter = 0,
  tst_count = document.getElementById('tst_count'),
  tst_btn = document.getElementById('tst_btn');

tst_btn.addEventListener('click', ()=>{
  var shouldIncrement = Math.random() > 0.5; // 50% chances of incrementing
  counter += shouldIncrement ? 1 : -1;
  tst_count.innerText = counter;
});
</script>
Demo:

0