Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • TypeScript Tutorial
  • TS Exercise
  • TS Interview Questions
  • TS Cheat Sheet
  • TS Array
  • TS String
  • TS Object
  • TS Operators
  • TS Projects
  • TS Union Types
  • TS Function
  • TS Class
  • TS Generic
Open In App
Next Article:
Simple Counter App Using HTML CSS and TypeScript
Next article icon

Simple Counter App Using HTML CSS and TypeScript

Last Updated : 22 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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

counter
Simple Counter App UsingTypeScript

Counter 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

  1. HTML Structure
    1. A container div holds the counter display and buttons for incrementing, decrementing, and resetting.
  2. CSS Styling
    1. Ensures a clean, centered layout with visually distinct buttons for each action.
    2. 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> 

Next Article
Simple Counter App Using HTML CSS and TypeScript

S

sneha2dmo
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • TypeScript
  • TypeScript-Projects

Similar Reads

    Create a Single Page Application using HTML CSS & JavaScript
    In this article, we are going to design and build a cool and user-friendly single-page application (SPA) using just HTML, CSS, and JavaScript. A single-page application contains multiple pages which can be navigated or visited without loading the page every time. This makes things faster and more in
    4 min read
    Typing Speed Detector App Using Typescript
    Typing speed has been a very important test for Engineers as a faster typing skill leads to faster code so, To test this speed we are building a typing speed detector.What We’re Going to CreateAn Input Box for Typing Our Text.A Time Element to show the time.An Element to show Words per minute.A star
    5 min read
    Calculator App Using TypeScript
    A calculator app is a perfect project for practising TypeScript along with HTML and CSS. This app will have basic functionalities like addition, subtraction, multiplication, and division. It provides a clean and interactive interface for the user while using TypeScript to handle logic safely and eff
    6 min read
    Quiz App Using Typescript
    A quiz app built with TypeScript provides an interactive way to test knowledge while using TypeScript’s strong typing for better code quality. By implementing features like multiple-choice questions, score tracking, and timers, we can create a robust and engaging quiz experience for users.What We’re
    7 min read
    Task Management App Using TypeScript
    Task management apps help users organize their daily activities effectively. In this article, we will create a simple task management app that allows users to add and delete tasks. We’ll use HTML for structure, CSS for styling, and TypeScript for functionality to make it robust and type-safe.What We
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences