Requirements :
- the counter implementation and it's usage must be on the same page
- the view consist of a single value and two buttons : inc and dec
Here is mine using DML library:
import {button, idiv} from "./dml"; /* <sdtio.h> :-) */
function Counter () {
let count = 0;
let value = idiv("0");
let binc = button("inc");
let bdec = button("dec");
binc.onclick = () => value.innerText = ++count;
bdec.onclick = () => value.innerText = --count;
}
Counter();
You can test it here : TinyCounter
Show yours :-)
Here is a better implementation from Eckehard, thanks to him :
import {button, idiv} from "./dml"; /* <sdtio.h> :-) */
function Counter () {
let value = idiv("0");
button("inc").onclick = () =>value.innerText = Number(value.innerText)+1
bdec = button("dec").onclick = () => value.innerText = Number(value.innerText)-1
}
Counter();
Top comments (2)
As you may know, it is not necessary to create variables for the buttons in this case. And removing the counter may not be very elegant, but removes the double storage of a value. It is generally advised to use the state of a DOM element directly to avoid misalignments:
Thank you very much Eckehard.
I appreciate your advises, don't hesitate :-)
Regards