Site icon FSIBLOG

How to Build a Simple Counter App with HTML and JavaScript

How to Build a Simple Counter App with HTML and JavaScript

Today we will create a simple Counter Application using HTMLTailwind CSS, and JavaScript. This app will allow users to increment or decrement a numeric value with the click of buttons. Let’s dive into the code and explanation!

Project Structure

We’ll create a basic structure for our CounterApp with the following files:

Setting Up HTML

Create an index.html file with the following content:

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Counter App</title>
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <link rel="stylesheet" href="styles.css">
</head>
<body class="flex items-center justify-center h-screen bg-gray-100">
    <div class="bg-white p-8 rounded-lg shadow-md text-center">
        <h1 class="text-2xl font-bold mb-4">Counter App</h1>
        <div id="counter" class="text-4xl font-semibold mb-4">0</div>
        <div>
            <button id="decrement" class="bg-red-500 text-white px-4 py-2 rounded-lg mr-2">Decrement</button>
            <button id="increment" class="bg-green-500 text-white px-4 py-2 rounded-lg">Increment</button>
        </div>
    </div>
    <script src="script.js"></script>
</body>
</html>

Explanation of HTML

Adding JavaScript Functionality

Next, create a script.js file with the following code:

javascript

let count = 0;

const counterDisplay = document.getElementById('counter');
const incrementButton = document.getElementById('increment');
const decrementButton = document.getElementById('decrement');

incrementButton.addEventListener('click', () => {
    count++;
    updateCounterDisplay();
});

decrementButton.addEventListener('click', () => {
    count--;
    updateCounterDisplay();
});

function updateCounterDisplay() {
    counterDisplay.textContent = count;
}

Explanation of JavaScript

Adding Custom Styles (Optional)

If you want to add some custom styles, you can create a styles.css file. For example:

css

body {
    font-family: 'Arial', sans-serif;
}

This is optional since Tailwind CSS provides a lot of utility classes for styling.

Conclusion

You now have a fully functional Counter Application built with HTMLTailwind CSS, and JavaScript! This project is a great way to practice your skills and understand how to manipulate the DOM with JavaScript. You can further enhance this app by adding features like reset functionality or saving the counter value in local storage. Happy coding!

Exit mobile version