quick question: Is it possible to set a button that can increment and or decrement a number as it is clicked? I want to know if such a feature is possible and if so, how?
Asked
Active
Viewed 211 times
0
-
Literally no, but with a button, you can start executing a script doing what you need. – Teemu Nov 30 '20 at 07:53
-
"literally no"??? You can do many things when clicking a button if you have added an event listener to it. @Teemu I think you are being cryptic here. Poor question but still – mplungjan Nov 30 '20 at 07:58
-
Please visit the [help], take the [tour] to see what and [ask]. Do some research, search for related topics on SO; if you get stuck, post a [mcve] of your attempt, noting input and expected output using the `[<>]` snippet editor. – mplungjan Nov 30 '20 at 07:59
-
[Flip a coin](https://www.google.com/search?q=javascript+flip+a+coin+site%3Astackoverflow.com) – mplungjan Nov 30 '20 at 08:03
-
@mplungjan You can submit a form with a button, but that's all what a button can do on its own. As you said, you'd need an event listener, and a script to handle that event. So, it's literally not possible for a button to increment or decrement a number. – Teemu Nov 30 '20 at 08:04
-
@Teemu Question was tagged JavaScript so we were likely allowed to use JS. And the button submitting to the server could have the server return incremented or decremented values... – mplungjan Nov 30 '20 at 08:06
-
@mplungjan The tongue in the cheek of course, and it's yet a better answer than [this](https://stackoverflow.com/a/65068527/1169519). – Teemu Nov 30 '20 at 08:13
-
@Teemu Lol...... – mplungjan Nov 30 '20 at 08:16
1 Answers
0
You can use Math.random()
to decide whether you are going to increment or not:
var counter = 0,
$counter = document.getElementById('counter'),
$myBtn = document.getElementById('myBtn');
$myBtn.addEventListener('click', incrementOrDecrement);
function incrementOrDecrement() {
var shouldIncrement = Math.random() > 0.5; // 50% chances of incrementing
counter += shouldIncrement ? 1 : -1;
$counter.innerText = counter;
}
<button id="myBtn">Change counter</button>
<h2 id="counter">0</h2>

blex
- 24,941
- 5
- 39
- 72