How to make Incremental and Decremental counter using HTML, CSS and JavaScript ?
Last Updated :
22 Dec, 2023
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.
Output Preview:
Approach:
- First, we will design a simple button using HTML. Refer to the comments in the code.
- 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.
- 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: In this example, we are following above explained approach.
Javascript
let data = 0;
document.getElementById( "counting" ).innerText = data;
function increment() {
data = data + 1;
document.getElementById( "counting" ).innerText = data;
}
function decrement() {
data = data - 1;
document.getElementById( "counting" ).innerText = data;
}
|
HTML
<!DOCTYPE HTML>
< html >
< head >
< meta http-equiv = "Content-Type"
content = "text/html; charset=UTF-8" />
</ head >
< body >
< h1 >Increment and Decrement counter</ h1 >
< div class = "container" >
< button onclick = "increment()" >+</ button >
< h2 id = "counting" ></ h2 >
< button onclick = "decrement()" >-</ button >
</ div >
</ body >
</ html >
|
CSS
body {
position : absolute ;
left : 0% ;
text-align : center ;
}
.container {
justify- content : center ;
align-items: center ;
display : flex;
height : 100% ;
text-align : center ;
}
button {
width : 90px ;
height : 60px ;
font-size : 30px ;
background-color : green ;
color : honeydew;
}
button:hover {
background-color : greenyellow;
color : grey;
}
h 2 {
color : black ;
margin : 0 50px ;
font-size : 45px ;
}
h 1 {
font-size : 35px ;
color : green ;
text-align : center ;
padding-left : 10% ;
}
|
Output: Click here to see live code output
Â
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...