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
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
Similar Topics
-
Random object from multiple arrays with percent chance in JS
JavaScript - jQuery - Ajax
First post
I have 3 arrays of objects in JavaScript:
const fruits =
const car =
const books =
One temporary array where I will store random objects...
Last post
You need to get two random numbers:
- the first to decide which group to pick,
- the second to pick an item from that.
We generate a random...
-
Stop button in Speech in Php
PHP - MySQL
First post
How are all things going CoursesWeb now with Covid-19.
It is shamble for all lovely lady`s who have the name.
I hope all Governements gonna make-up...
Last post
I could kiss you for this support all things working & I even have it now in Dutch
Thanks Coursesweb
-
php mail two forms one button
PHP - MySQL
First post
Hello I found a mail script with add file`s function
only I would like to build a seccond mail-function
in it so the sender gets a copy from his...
Last post
Still mutch thanks for your support like allway`s