While visiting different shopping websites like Flipkart and Amazon you have seen a counter on each product, that counter is used to specify the quantity of that product. Hence, the counter is a very useful part of many websites. In this article, we will design a counter using HTML, CSS, and JavaScript.
A sample image is provided to give you a more clear idea about the article.
Step-by-step implementation:
Step 1: First, we will design a simple button using HTML. Refer to the comments in the code.
Step 2: Next, we will use some CSS properties to design the button and use the hover class to get the animation effect when we hover the mouse over the button.
Step 3: Now, we will add some JavaScript code to add functionality to the buttons which we created earlier. Refer to the comments in the code for help.
Example:
HTML
<!DOCTYPE HTML>Â
<html>Â
<head>Â Â Â Â <meta http-equiv="Content-Type"Â Â Â Â Â Â Â Â content="text/html; charset=UTF-8" />Â Â Â Â Â </head>Â Â Â Â Â <body><!-- give a suitable heading using h1 tag-->Â Â Â Â Â Â Â Â <h1>Increment and Decrement counter</h1>Â
        <div class="container">                   <!-- adding button and heading to show the digits -->        <!--increment() and decrement() functions on button click-->            <button onclick="increment()">+</button>            <h2 id="counting"></h2>            <button onclick="decrement()">-</button>               </div>Â
</body>Â
</html> |
CSS
/*apply css properties to body tag*/Â
body {Â Â Â Â position: absolute;Â Â Â Â left: 0%;Â Â Â Â text-align: center;}Â
/*apply css properties to container class*/Â
.container {Â Â Â Â justify-content: center;Â Â Â Â align-items: center;Â Â Â Â display: flex;Â Â Â Â height: 100%;Â Â Â Â text-align: center;}Â
/*apply css properties to button tag*/Â
button {Â Â Â Â width: 90px;Â Â Â Â height: 60px;Â Â Â Â font-size: 30px;Â Â Â Â background-color: green;Â Â Â Â color: honeydew;}Â
/*apply hover effect to button tag*/Â
button:hover {Â Â Â Â background-color: greenyellow;Â Â Â Â color: grey;}Â
/*apply css properties to h2 tag*/Â
h2 {Â Â Â Â color: black;Â Â Â Â margin: 0 50px;Â Â Â Â font-size: 45px;}Â
/*apply css properties to h1 tag*/Â
h1 {Â Â Â Â font-size: 35px;Â Â Â Â color: green;Â Â Â Â text-align: center;Â Â Â Â padding-left: 10%;} |
Javascript
//initialising a variable name dataÂ
let data = 0;Â
//printing default value of data that is 0 in h2 tagdocument.getElementById("counting").innerText = data;Â
//creation of increment functionfunction increment() {Â Â Â Â data = data + 1;Â Â Â Â document.getElementById("counting").innerText = data;}//creation of decrement functionfunction decrement() {Â Â Â Â data = data - 1;Â Â Â Â document.getElementById("counting").innerText = data;} |
Output: Click here to see live code output
Â

