Introduction
One of the useful functionalities that you may need to have on your website is a counter that counts the views of your web pages. The easiest way to do that is through the CountAPI which gives you this amazing functionality.
In this article, we will learn how to count our page views using the CountAPI in JavaScript. Let's get right into it.
The CountAPI
This API allows you to make numeric counters. It's a very useful API to track the number of hits a page received. It also allows you to know the number of users that clicked on a button for example. So it also counts events.
The CountAPI provides a hit endpoint each time it is called, the counter will increase by one.
Check it out in the link below:
https://api.countapi.xyz/hit/namespace/key
You should know that each counter is identified inside a namespace with a key. The namespace should be unique, so you need to replace it with your website domain.
Example
Let's say you want to count and display your web page views, the CountAPI allows you to do that by using their NPM package, JSONP, XHR, or jQuery.
In the example below, we will use JSONP. You can check the other ways on their website later.
The first thing we will do is creating our HTML:
<body>
<h1>This page got <span id="visits"></span> views.</h1>
</body>
In the head tag, you will have to add a script CDN for the CountAPI. It will be like the following:
<head>
<script async src="https://api.countapi.xyz/hit/mysite.com/visits? callback=callbackName"></script>
</head>
You will have to replace the mysite.com with your own domain. Also, replace the callbackName with any callback name that we will create below in JavaScript.
Now we will go to JavaScript in order to create a callback that will get the number of visits and replace it inside the element that has an ID visits .
function callbackName(response) {
document.getElementById('visits').innerText = response.value;
}
We will not call this function because it's already called on the CDN above.
Here is the Codepen example if you want to check it out:
As you can see, this is the easiest way to count the views that your web page received.
Conclusion
The CountAPI makes it easier to count page views and display them on the page. This API also has some more functionalities that I encourage you to check on their website.
Thank you for reading this article, I hope you found it useful.
More Reading
If you are also interested in more useful content related to JavaScript and web development, you can also subscribe to my newsletter.
Here is another useful article to check out.