JSFiddle - React, Tailwind, and code Playground

by Alaksandar Jesus Gene

HTML

<h1>Counter App</h1>

<div id="counter" style="margin-top: 10px; margin-bottom: 10px"></div>

<!-- Method One -->
<h1>Method 1</h1>
<button onclick="onBtnClick(1)">+1</button>
<button onclick="onBtnClick(-1)">-1</button>

<!-- Method Two -->
<h1>Method 2</h1>
<button class="btn" data-value="1">+1</button>
<button class="btn" data-value="-1">-1</button>

JavaScript

const counterEle = document.getElementById('counter'); // get the counter display element
let counter = 0; // let the starting value of counter = 0
counterEle.innerText = counter; //set the counter value to the element to display  in html


function onBtnClick(val) {
  counter = counter + parseInt(val); // parseInt to convert to integer
  counterEle.innerText = counter; // update the counter text
}


/* Method 2 */
document.querySelectorAll('.btn').forEach(function (ele) {
  ele.addEventListener('click', function (event) {
    const value = event.target.getAttribute('data-value');
    onBtnClick(value);
  });
});