Creating a Counter with HTML, CSS, and JavaScript (Source Code)

Faraz

By Faraz -

Learn how to create an interactive counter for your website using HTML, CSS, and JavaScript. Perfect for web development beginners.


Creating a Counter with HTML, CSS, and JavaScript.jpg

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Preview
  6. Conclusion

Are you a budding web developer eager to add interactive elements to your website? One great place to start is by creating a counter! In this tutorial, we will guide you through building a counter from scratch using HTML, CSS, and JavaScript. Whether you're a complete beginner or looking to expand your web development skills, this step-by-step guide is for you.

Let's start making a counter using HTML, CSS, and JavaScript step by step.

Join My Telegram Channel to Download the Project Source Code: Click Here

Prerequisites:

Before starting this tutorial, you should have a basic understanding of HTML, CSS, and JavaScript. Additionally, you will need a code editor such as Visual Studio Code or Sublime Text to write and save your code.

Source Code

Step 1 (HTML Code):

To get started, we will first need to create a basic HTML file. In this file, we will include the main structure for our counter.

After creating the files just paste the following codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.

Let's break it down step by step:

1. <!DOCTYPE html>: This declaration specifies the document type and version of HTML being used. In this case, it's HTML5.

2. <html lang="en">: This is the root element of the HTML document. The lang attribute specifies the language of the document, which is set to English (en).

3. <head>: This section contains metadata about the web page, which is not visible to users but is important for browsers and search engines.

  • <meta charset="UTF-8">: This meta tag defines the character encoding for the document, which is UTF-8. UTF-8 is a character encoding that supports a wide range of characters, including those from various languages.
  • <meta name="viewport" content="width=device-width, initial-scale=1.0">: This meta tag sets the viewport settings for responsive web design. It tells the browser to adjust the width of the page to the device's screen width and sets the initial zoom level to 1.0.
  • <title>Counter</title>: This sets the title of the web page to "Counter," which appears in the browser's title bar or tab.
  • <link rel="stylesheet" href="styles.css">: This line includes an external stylesheet called "styles.css." Stylesheets are used to define the visual presentation (e.g., colors, fonts) of the web page.

4. <body id="body">: This is the body of the web page where the visible content is placed.

5. <button type="button" class="btn changemode">Switch Dark mode</button>: This is a button element with a class "btn" and "changemode." It will be used to toggle between dark and light modes on the page.

6. <main>: This is a semantic HTML5 element that represents the main content of the web page.

7. <div class="container">: This is a div element with a class "container" that serves as a container for the content within it.

8. <h1>counter</h1>: This is a level 1 heading element that displays the text "counter."

9. <span id="value">0</span>: This is a span element with an id "value" that initially displays the number "0." It can be used to dynamically update and display a counter value.

10. <div class="button-container">: This div with the class "button-container" serves as a container for a group of buttons.

11. Three buttons:

  • <button class="btn decrease">decrease</button>: A button with a class "btn" and "decrease" that is used to decrease the counter value.
  • <button class="btn reset">reset</button>: A button with a class "btn" and "reset" that is used to reset the counter value.
  • <button class="btn increase">increase</button>: A button with a class "btn" and "increase" that is used to increase the counter value.

12. <script src="script.js"></script>: This line includes an external JavaScript file called "script.js." JavaScript is used to add interactivity and functionality to the web page.

This is the basic structure of our counter using HTML, and now we can move on to styling it using CSS.

Step 2 (CSS Code):

Once the basic HTML structure of the counter is in place, the next step is to add styling to the counter using CSS.

Next, we will create our CSS file. In this file, we will use some basic CSS rules to style our counter. Let's break down what each part of the code does:

1. @import url("https://fonts.googleapis.com/css?family=Open+Sans|Roboto:400,700&display=swap");

  • This line imports two Google Fonts, "Open Sans" and "Roboto" with two weights (400 and 700) for later use in the CSS.

2. :root { ... }

  • This defines CSS custom properties (variables) inside the :root pseudo-class. These variables are used to store values that can be reused throughout the stylesheet.

3. *, ::after, ::before { ... }

  • These selectors are used to reset the default margin, padding, and box-sizing for all elements on the page, ensuring a consistent layout.

4. body { ... }

  • Defines styles for the body element, including font family, background color, text color, line-height, and font size.

5. ul { ... }

  • Styles for unordered lists to remove bullets.

6. a { ... }

  • Styles for anchor (link) elements to remove underlines.

7. h1, h2, h3, h4 { ... }

  • Styles for headings (h1, h2, h3, h4) including letter spacing, text transformation, line height, margin, and font family. These styles make headings look consistent and visually appealing.

8. Media Queries (@media screen and (min-width: 800px) { ... })

  • These styles apply only when the screen width is at least 800px. It adjusts font sizes and line heights for headings and body text to make the design responsive.

9. .section { ... }

  • Styles for elements with the class "section," including padding.

10. .section-center { ... }

  • Styles for elements with the class "section-center," setting the width and margins to center the content. It also limits the maximum width to 1170px.

11. .container { ... }

  • Styles for elements with the class "container," defining text alignment.

12. #value { ... }

  • Styles for an element with the ID "value," setting the font size and font weight.

13. .btn { ... }

  • Styles for elements with the class "btn" (buttons), including text transformation, background color, text color, padding, letter spacing, and various other properties for button styling.

14. .btn:hover { ... }

  • Styles for button hover states, changing the text and background colors to create an interactive effect when a user hovers over a button.

15. .darkbody { ... } and .darkbutton { ... }

  • These classes define styles for creating a dark mode theme. They change the background color, text color, and border color for specific elements to create a dark color scheme.

16. .darkbutton:hover { ... }

  • Styles for the dark mode button hover state, changing text and background colors when hovering over a button in dark mode.

This will give our counter an upgraded presentation. Create a CSS file with the name of styles.css and paste the given codes into your CSS file. Remember that you must create a file with the .css extension.

@import url("https://fonts.googleapis.com/css?family=Open+Sans|Roboto:400,700&display=swap");

:root {
    --clr-primary-1: hsl(205, 86%, 17%);
    --clr-primary-2: hsl(205, 77%, 27%);
    --clr-primary-3: hsl(205, 72%, 37%);
    --clr-primary-4: hsl(205, 63%, 48%);
    --clr-primary-5: hsl(205, 78%, 60%);
    --clr-primary-6: hsl(205, 89%, 70%);
    --clr-primary-7: hsl(205, 90%, 76%);
    --clr-primary-8: hsl(205, 86%, 81%);
    --clr-primary-9: hsl(205, 90%, 88%);
    --clr-primary-10: hsl(205, 100%, 96%);
    --clr-grey-1: hsl(209, 61%, 16%);
    --clr-grey-2: hsl(211, 39%, 23%);
    --clr-grey-3: hsl(209, 34%, 30%);
    --clr-grey-4: hsl(209, 28%, 39%);
    --clr-grey-5: hsl(210, 22%, 49%);
    --clr-grey-6: hsl(209, 23%, 60%);
    --clr-grey-7: hsl(211, 27%, 70%);
    --clr-grey-8: hsl(210, 31%, 80%);
    --clr-grey-9: hsl(212, 33%, 89%);
    --clr-grey-10: hsl(210, 36%, 96%);
    --clr-white: #fff;
    --clr-red-dark: hsl(360, 67%, 44%);
    --clr-red-light: hsl(360, 71%, 66%);
    --clr-green-dark: hsl(125, 67%, 44%);
    --clr-green-light: hsl(125, 71%, 66%);
    --clr-black: #222;
    --ff-primary: "Roboto", sans-serif;
    --ff-secondary: "Open Sans", sans-serif;
    --transition: all 0.3s linear;
    --spacing: 0.1rem;
    --radius: 0.25rem;
    --light-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
    --dark-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
    --max-width: 1170px;
    --fixed-width: 620px;
}

*,
::after,
::before {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: var(--ff-secondary);
    background: var(--clr-grey-10);
    color: var(--clr-grey-1);
    line-height: 1.5;
    font-size: 0.875rem;
}

ul {
    list-style-type: none;
}

a {
    text-decoration: none;
}

h1,
h2,
h3,
h4 {
    letter-spacing: var(--spacing);
    text-transform: capitalize;
    line-height: 1.25;
    margin-bottom: 0.75rem;
    font-family: var(--ff-primary);
}

h1 {
    font-size: 3rem;
}

h2 {
    font-size: 2rem;
}

h3 {
    font-size: 1.25rem;
}

h4 {
    font-size: 0.875rem;
}

p {
    margin-bottom: 1.25rem;
    color: var(--clr-grey-5);
}

@media screen and (min-width: 800px) {
    h1 {
        font-size: 4rem;
    }
    h2 {
        font-size: 2.5rem;
    }
    h3 {
        font-size: 1.75rem;
    }
    h4 {
        font-size: 1rem;
    }
    body {
        font-size: 1rem;
    }
    h1,
    h2,
    h3,
    h4 {
        line-height: 1;
    }
}

.section {
    padding: 5rem 0;
}

.section-center {
    width: 90vw;
    margin: 0 auto;
    max-width: 1170px;
}

@media screen and (min-width: 992px) {
    .section-center {
        width: 95vw;
    }
}

main {
    min-height: 100vh;
    display: grid;
    place-items: center;
}

main {
    min-height: 100vh;
    display: grid;
    place-items: center;
}

.container {
    text-align: center;
}

#value {
    font-size: 6rem;
    font-weight: bold;
}

.btn {
    text-transform: uppercase;
    background: transparent;
    color: var(--clr-black);
    padding: 0.375rem 0.75rem;
    letter-spacing: var(--spacing);
    display: inline-block;
    transition: var(--transition);
    font-size: 0.875rem;
    border: 2px solid var(--clr-black);
    cursor: pointer;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
    border-radius: var(--radius);
    margin: 0.5rem;
}

.btn:hover {
    color: var(--clr-white);
    background: var(--clr-black);
}

.darkbody{
    background-color: black;
    color: var(--clr-primary-6);
}
.darkbutton{
    text-transform: uppercase;
    background: transparent;
    color: var(--clr-white);
    padding: 0.375rem 0.75rem;
    letter-spacing: var(--spacing);
    display: inline-block;
    transition: var(--transition);
    font-size: 0.875rem;
    border: 2px solid var(--clr-white);
    cursor: pointer;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
    border-radius: var(--radius);
    margin: 0.5rem;   
}
.darkbutton:hover{
    color: var(--clr-black);
    background: var(--clr-white);
} 

Step 3 (JavaScript Code):

Finally, we need to create a function in JavaScript. Let's break down the code step by step:

1. The code starts by selecting elements from the HTML document using the document.getElementById and document.querySelector methods:

  • const value: This variable represents an HTML element with the id 'value', presumably a text element that displays a numeric value.
  • const btn1, const btn2, const btn3: These variables represent buttons with class names 'decrease', 'reset', and 'increase', respectively. These buttons are used to decrease, reset, and increase the displayed value.
  • const btnmode: This variable represents a button with the class name 'changemode'. This button is used to toggle between light and dark modes.

2. A variable number is declared and initialized to 0. This variable will store the numeric value that is displayed on the web page.

3. Event listeners are added to the buttons to handle user interactions:

  • btn1.addEventListener('click', function() { ... }): When the 'decrease' button is clicked, this function is executed. It decreases the number variable by 1, updates the text content of the 'value' element, and changes the text color to red.
  • btn2.addEventListener('click', function() { ... }): When the 'reset' button is clicked, this function is executed. It sets the number variable and the text content of the 'value' element to 0 and changes the text color to a shade of blue.
  • btn3.addEventListener('click', function() { ... }): When the 'increase' button is clicked, this function is executed. It increases the number variable by 1, updates the text content of the 'value' element, and changes the text color to green.

4. Another event listener is added to the btnmode button:

  • btnmode.addEventListener('click', function() { ... }): When the 'changemode' button is clicked, this function is executed. It toggles a CSS class 'darkbody' on the 'body' element, effectively switching between light and dark modes. It also changes the text content of the 'btnmode' button to toggle between "Switch Light Mode" and "Switch Dark Mode". Additionally, it toggles a 'darkbutton' class on the buttons (btn1, btn2, btn3, and btnmode) to adjust their appearance in dark mode.

Create a JavaScript file with the name script.js and paste the given codes into your JavaScript file and make sure it's linked properly to your HTML document so that the scripts are executed on the page. Remember, you’ve to create a file with .js extension.

const value = document.getElementById('value');
const btn1 = document.querySelector('.decrease');
const btn2 = document.querySelector('.reset');
const btn3 = document.querySelector('.increase');
const btnmode=document.querySelector('.changemode');

let number = 0;
btn1.addEventListener('click', function() {
    value.textContent = --number;
    value.style.color = "red";
});
btn2.addEventListener('click', function() {
    value.textContent = 0;
    number = 0;
        value.style.color = "hsl(210, 22%, 49%)";
    
});
btn3.addEventListener('click', function() {
    value.textContent = ++number;
    value.style.color = "green";
});

btnmode.addEventListener('click',function(){
    let body =document.getElementById('body');
    body.classList.toggle("darkbody");
    let text = btnmode.innerHTML;
    if(text=="Switch Light Mode"){
        btnmode.innerHTML="Switch Dark Mode"
    }
    else{
        btnmode.innerHTML="Switch Light Mode"
    }
    btn1.classList.toggle("darkbutton")
    btn2.classList.toggle("darkbutton")
    btn3.classList.toggle("darkbutton")
    btnmode.classList.toggle("darkbutton")
})

Final Output:

Creating a Counter with HTML, CSS, and JavaScript.gif

Conclusion:

Congratulations! You've successfully created a counter using HTML, CSS, and JavaScript. This tutorial is just the beginning of your web development journey. Feel free to experiment, customize, and add more features to your counter. Happy coding!

After completing this tutorial, you're on your way to becoming a skilled web developer. Stay curious and keep building!

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post