Hello Coders! Welcome to JS Project Blog. In this, we're going to see how to create a Website Visits Counter using JavaScript. You might know every website tracks the number of visitors it gets on a daily basis. It allows business to know their audience and the count of the audience. This is one simple example on how you can add a counter which tracks the number of website visitors.
Here's a preview-
That being said, let us get started.
Step - 1: Like always, create 3 files - index.html, style.css and script.js
Step - 2: Copy the below HTML code and paste it into your code editor.
HTML
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>Website visit counter</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<html>
<head>
<title>Website Counter</title>
<script defer src="index.js"></script>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<div>Website visit count:</div>
<div class="website-counter"></div>
<button id="reset">Reset</button>
</body>
</html>
<script src="./script.js"></script>
</body>
</html>
Step - 3: Below is the CSS code for styling.
CSS
@import url('https://fonts.googleapis.com/css2?family=Poppins&display=swap');
body, .website-counter {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
font-family: 'Poppins', sans-serif;
font-weight: 800;
background: #f6f7fc;
}
body {
height: 100vh;
}
.website-counter {
background-color: #b74096;
height: 50px;
width: 80px;
color: white;
border-radius: 30px;
font-weight: 700;
font-size: 25px;
margin-top: 10px;
}
#reset {
margin-top: 60px;
background-color: #008cba;
cursor: pointer;
font-size: 18px;
padding: 8px 20px;
color: white;
border: 0;
border-radius: 20px;
}
Step - 3: Below is the jQuery code for adding and removing the class.
JS
var counterContainer = document.querySelector(".website-counter");
var resetButton = document.querySelector("#reset");
var visitCount = localStorage.getItem("page_view");
// Check if page_view entry is present
if (visitCount) {
visitCount = Number(visitCount) + 1;
localStorage.setItem("page_view", visitCount);
} else {
visitCount = 1;
localStorage.setItem("page_view", 1);
}
counterContainer.innerHTML = visitCount;
// Adding onClick event listener
resetButton.addEventListener("click", () => {
visitCount = 1;
localStorage.setItem("page_view", 1);
counterContainer.innerHTML = visitCount;
});
And that's it. You're done.
Let me know in the comments if you have any doubt related to this.
Follow @creocodigo for more projects and web related content.
If you find this useful, below are some other posts that I am sure you'll love