A simple javascript counter using HTML, CSS and Javascript
Stay tuned for more tutorials like this.
Video Tutorial and source code is given below
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple counter using HTML, CSS, JS</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="whole">
<div class="main">
<div class="counter">9</div>
<div class="plus count"><i class="fa-solid fa-plus"></i></div>
<div class="minus count"><i class="fa-solid fa-minus"></i></div>
</div>
<div class="reset">
<button class="reset-btn">Reset</button>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
Create a file in same directory and name it style.css
paste the code given below
@import url('https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,700&display=swap');
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body{
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
font-family: 'Roboto', sans-serif;
}
.whole{
margin: auto;
}
.main{
width: 300px;
position: relative;
}
.main .counter{
width: 200px;
height: 200px;
margin: auto;
display: flex;
text-align: center;
justify-content: center;
align-items: center;
background-color: #FF5757;
border-radius: 5px;
font-size: 5rem;
font-weight: 700;
color: #fff;
}
.count{
position: absolute;
width: 80px;
height: 80px;
background-color: #fff;
border: 5px solid #FF5757;
display: flex;
align-items: center;
justify-content: center;
bottom: -30px;
border-radius: 5px;
}
.count i{
color: #FF5757;
font-size: 2rem;
}
.count:hover{
box-shadow: rgba(50, 50, 93, 0.25) 0px 13px 27px -5px, rgba(0, 0, 0, 0.3) 0px 8px 16px -8px;
}
.plus{
right: 10px;
}
.minus{
left: 10px;
}
.reset{
align-items: center;
text-align: center;
margin-top: 80px;
}
.reset .reset-btn{
margin: auto;
outline: none;
padding: 10px 18px;
background-color: #fff;
border-radius: 5px;
border: 5px solid #FF5757;
color: #FF5757;
font-size: 1.2rem;
font-weight: 700;
}
.reset .reset-btn:hover{
background-color: #FF5757;
color: #fff;
}
And finally a Javascript file name it as app.js
const counter = document.querySelector('.counter');
const add = document.querySelector('.plus')
const sub = document.querySelector('.minus')
const resetNum = document.querySelector('.reset-btn')
let number = counter.innerHTML;
add.addEventListener('click', function(){
number++;
addToHtml(number);
})
sub.addEventListener('click', function(){
number--;
addToHtml(number);
})
resetNum.addEventListener('click', function(){
addToHtml(0);
})
function addToHtml(value){
number = value;
counter.innerHTML = value;
}
addToHtml(0)
Thanks for reading
If any suggestions please let me know
I am happy to talk with you
Top comments (0)