Simple Counter App Using HTML CSS and TypeScript
Last Updated :
22 Jan, 2025
A simple counter app is a great project for learning how to integrate HTML, CSS, and TypeScript. The app will allow users to increment, decrement, and reset the counter value, demonstrating essential DOM manipulation and event handling in TypeScript.
What We’re Going to Create
We’ll build a counter app with the following features:
- Increment the counter value.
- Decrement the counter value (but not below zero).
- Reset the counter to zero.
Project Preview
Simple Counter App UsingTypeScriptCounter App - HTML and CSS Setup
Below is the combined HTML and CSS code that structures and styles the counter app
HTML
<html>
<head>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.container {
text-align: center;
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
h1 {
margin-bottom: 20px;
}
.counter {
font-size: 3rem;
margin: 20px 0;
}
.buttons button {
padding: 10px 20px;
margin: 5px;
font-size: 1rem;
cursor: pointer;
border: none;
border-radius: 4px;
transition: background 0.3s;
}
#increment {
background: #4caf50;
color: white;
}
#decrement {
background: #f44336;
color: white;
}
#reset {
background: #2196f3;
color: white;
}
.buttons button:hover {
opacity: 0.8;
}
</style>
</head>
<body>
<div class="container">
<h1>Counter App</h1>
<div id="counter" class="counter">0</div>
<div class="buttons">
<button id="increment">Increment</button>
<button id="decrement">Decrement</button>
<button id="reset">Reset</button>
</div>
</div>
<script>
var counter = document.getElementById('counter');
var incrementBtn = document.getElementById('increment');
var decrementBtn = document.getElementById('decrement');
var resetBtn = document.getElementById('reset');
var count = 0;
function updateCounter() {
counter.textContent = count.toString();
}
incrementBtn.addEventListener('click', function () {
count++;
updateCounter();
});
decrementBtn.addEventListener('click', function () {
if (count > 0) {
count--;
updateCounter();
}
});
resetBtn.addEventListener('click', function () {
count = 0;
updateCounter();
});
</script>
</body>
</html>
Explanation of the Code
- HTML Structure
- A container div holds the counter display and buttons for incrementing, decrementing, and resetting.
- CSS Styling
- Ensures a clean, centered layout with visually distinct buttons for each action.
- Includes hover effects for an enhanced user experience.
Counter App – TypeScript Logic
The TypeScript code handles the counter's functionality, including updating the counter value and managing button clicks.
JavaScript
const counter = document.getElementById('counter') as HTMLDivElement;
const incrementBtn = document.getElementById('increment') as HTMLButtonElement;
const decrementBtn = document.getElementById('decrement') as HTMLButtonElement;
const resetBtn = document.getElementById('reset') as HTMLButtonElement;
let count = 0;
function updateCounter() {
counter.textContent = count.toString();
}
incrementBtn.addEventListener('click', () => {
count++;
updateCounter();
});
decrementBtn.addEventListener('click', () => {
if (count > 0) {
count--;
updateCounter();
}
});
resetBtn.addEventListener('click', () => {
count = 0;
updateCounter();
});
In this example
- Selects HTML elements for the counter and buttons.
- Initializes the counter value (
count
) to 0
. - Defines a function (
updateCounter()
) to update the displayed count. - Adds event listeners to buttons:
- Increment button increases the counter by 1.
- Decrement button decreases the counter by 1.
- Reset button sets the counter back to 0.
- Uses TypeScript type casting for type safety.
Convert to JavaScript File
Now You need to convert the TypeScript file into JavaScript to render by browser. Use one of the following command-
npx tsc task.ts
tsc task.ts
- The command tsc task.ts compiles the calculator.ts TypeScript file into a task.js JavaScript file.
- It places the output in the same directory as the input file by default.
Complete Code
HTML
<html>
<head>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.container {
text-align: center;
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
h1 {
margin-bottom: 20px;
}
.counter {
font-size: 3rem;
margin: 20px 0;
}
.buttons button {
padding: 10px 20px;
margin: 5px;
font-size: 1rem;
cursor: pointer;
border: none;
border-radius: 4px;
transition: background 0.3s;
}
#increment {
background: #4caf50;
color: white;
}
#decrement {
background: #f44336;
color: white;
}
#reset {
background: #2196f3;
color: white;
}
.buttons button:hover {
opacity: 0.8;
}
</style>
</head>
<body>
<div class="container">
<h1>Counter App </h1>
< div id="counter" class="counter"> 0
</div>
< div class="buttons">
<button id="increment"> Increment </button>
< button id="decrement"> Decrement </button>
< button id="reset"> Reset </button>
</div>
</div>
<script>
// Select elements from the DOM
var counter = document.getElementById('counter');
var incrementBtn = document.getElementById('increment');
var decrementBtn = document.getElementById('decrement');
var resetBtn = document.getElementById('reset');
// Initialize counter value
var count = 0;
// Update counter display
function updateCounter() {
counter.textContent = count.toString();
}
// Increment button event listener
incrementBtn.addEventListener('click', function () {
count++;
updateCounter();
});
// Decrement button event listener
decrementBtn.addEventListener('click', function () {
if (count > 0) {
count--; // Only decrement if count is greater than 0
updateCounter();
}
});
// Reset button event listener
resetBtn.addEventListener('click', function () {
count = 0;
updateCounter();
});
</script>
</body>
</html>
Similar Reads
TypeScript Tutorial TypeScript is a superset of JavaScript that adds extra features like static typing, interfaces, enums, and more. Essentially, TypeScript is JavaScript with additional syntax for defining types, making it a powerful tool for building scalable and maintainable applications.Static typing allows you to
8 min read
Difference between TypeScript and JavaScript Ever wondered about the difference between JavaScript and TypeScript? If you're into web development, knowing these two languages is super important. They might seem alike, but they're actually pretty different and can affect how you code and build stuff online.In this article, we'll break down the
4 min read
TypeScript Interview Questions and Answers TypeScript, a robust, statically typed superset of JavaScript, has become a go-to language for building scalable and maintainable applications. Developed by Microsoft, it enhances JavaScript by adding static typing and modern ECMAScript features, enabling developers to catch errors early and improve
15+ min read
TypeScript Map TypeScript Map is a collection that stores key-value pairs, where keys and values can be of any type. It maintains the insertion order of keys and provides methods to add, retrieve, check, remove, and clear entries, ensuring efficient management of key-value data.Creating a MapA map can be created a
3 min read
Typescript Set A Set in TypeScript is a bunch of unique values. It is part of the ECMAScript 2015 (ES6) standard and is implemented as a native object in JavaScript.Unlike arrays, sets do not allow duplicate elements, making them useful for storing collections of unique items. TypeScript provides strong typing for
3 min read
TypeScript Array map() Method The Array.map() is an inbuilt TypeScript function that creates a new array with the results of calling a provided function on every element in the array.Syntax:array.map(callback[, thisObject])Parameters: This method accepts two parameters as mentioned above and described below: callback: This param
2 min read
Introduction to TypeScript TypeScript is a syntactic superset of JavaScript that adds optional static typing, making it easier to write and maintain large-scale applications.Allows developers to catch errors during development rather than at runtime, improving code reliability.Enhances code readability and maintainability wit
5 min read
How to Format Date in TypeScript ? Formatting dates is important especially when displaying them to the users or working with date-related data. TypeScript provides various ways to achieve this. Below are the methods to format the date data type in TypeScript:Table of ContentUsing toLocaleString() methodUsing toLocaleDateString() met
3 min read
Data types in TypeScript In TypeScript, a data type defines the kind of values a variable can hold, ensuring type safety and enhancing code clarity.Primitive Types: Basic types like number, string, boolean, null, undefined, and symbol.Object Types: Complex structures including arrays, classes, interfaces, and functions.Prim
3 min read
How do I Remove an Array Item in TypeScript? In this article, we will learn about the different ways of removing an item from an array in TypeScript. In TypeScript, an array can be defined using union typing if it contains items of different types. We can use the following methods to remove items from a TypeScript array:Table of ContentUsing t
4 min read