DEV Community

Cover image for 🟨 JavaScript 3 | **Simple Counter**
Gregor Schafroth
Gregor Schafroth

Posted on

🟨 JavaScript 3 | **Simple Counter**

New day new JavaScript beginner Exercise! Here is what I got from ChatGPT today, and my solution below as always 😊

Create a Simple Counter

Objective: Build a web page with a button that, when clicked, increments a counter. This exercise will help you practice handling user events (like button clicks) and updating the webpage dynamically.

Steps:

  1. HTML Setup: Create an HTML file with a button and a placeholder to display the counter's value.
  2. Initialize the Counter: In your JavaScript, start with a variable set to zero. This will keep track of the counter's value.
  3. Increase Counter on Button Click: Add an event listener to the button so that each time it's clicked, the counter variable increases by 1.
  4. Display the Counter: Update the counter display on the webpage each time the button is clicked.
  5. Styling (Optional): Add some basic CSS to make your button and counter display look nice.

My Code

Alright I am starting to get annoyed that I can’t remember the JavaScript syntax out of my head, because I was mostly able to do that with Python. But I guess that’s exactly why python is getting so popular: It’s so easy and obvious

Well anyways that doesn’t help me here. Instead I decided to recreate todays code so often until I can just write it on my own without any help of ChatGPT. Took me 4 attempts until I finally was able to do even tho it is so simple, phewww

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple Counter 4</title>
</head>
<body>
    <h1 id="countDisplay">0</h1>
    <button id="countButton">Count</button>
    <script>
        let countDisplay = document.getElementById('countDisplay');
        let countButton = document.getElementById('countButton');
        let counter = 0;

        function incrementCounter() {
            counter++;
            countDisplay.textContent = counter;
        }

        countButton.addEventListener('click', incrementCounter)

    </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs