Skip to main content

Simple JavaScript Counter

Submitted by admin on Mon, 06/06/2022 - 21:38
javascript-counter

In this JavaScript tutorial we will create a simple counter with few buttons. On clicking the buttons, the value of counter will increase or decrease.

Create Counter with Few Buttons

Below code will create a region where the counter value will be displayed. And 4 buttons that will call a JavaScript function on click. On clicking these buttons the value of counter will increase or decrease.
We will also create a reset button.


<h3>Counter Value: <span id="counter-value">0</span></h3>
<button type="button" onclick="counterFunction(1)">Increase By one</button> <button type="button" onclick="counterFunction(-1)">Decrease By one</button>
<br /><br />
<button type="button" onclick="counterFunction(5)">Increase By Five</button> <button type="button" onclick="counterFunction(-5)">Decrease By Five</button>
<br /><br />
<button type="button" onclick="counterResetFunction()">Reset Counter</button>

JavaScript


let counter = 0;
const conterVal = document.querySelector("#counter-value");
// Increment Decrement function
function counterFunction(x) {
  counter += x;
  conterVal.innerHTML = counter;
}
// counter reset function
function counterResetFunction() {
  counter = 0;
  conterVal.innerHTML = counter;
}

Demo

Demo – Simple JavaScript Counter

Category

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.