Counter App In JavaScript

This counter app works by first displaying a number inside an <h1> element, which starts at 0, and storing that value in a JavaScript variable called count. When you click any button, it calls a specific JavaScript function using the onclick attribute. The Increase button runs the increase() function, which adds 1 to the count variable and then updates the displayed number by selecting the <h1> element using document.getElementById("count") and changing its innerText. The Decrease button works the same way but subtracts 1 from count using the decrease() function. The Reset button calls the reset() function, which sets count back to 0 and updates the display again. In short, the logic is: store a value in a variable, change that value when a button is clicked, and immediately reflect the new value on the webpage using DOM manipulation.

<!DOCTYPE html>
<html>
<head>
  <title>Counter App</title>
</head>
<body>

  <!-- Heading to show the counter value -->
  <h1 id="count">0</h1>

  <!-- Button to increase count -->
  <button onclick="increase()">Increase</button>

  <!-- Button to decrease count -->
  <button onclick="decrease()">Decrease</button>

  <!-- Button to reset count -->
  <button onclick="reset()">Reset</button>

  <!-- Link JavaScript file -->
  <script src="script.js"></script>

</body>
</html>
// Create a variable to store count value
let count = 0;

// Function to increase the count
function increase() {
  count = count + 1;               // Add 1 to count
  document.getElementById("count").innerText = count; // Update text
}

// Function to decrease the count
function decrease() {
  count = count - 1;               // Subtract 1 from count
  document.getElementById("count").innerText = count; // Update text
}

// Function to reset the count
function reset() {
  count = 0;                       // Set count back to 0
  document.getElementById("count").innerText = count; // Update text
}

Leave a Reply

Your email address will not be published. Required fields are marked *