- Add the following code in the
<head>section of your HTML document:
- Add the following code where you want to display the number of visitors on your website:
<p>Number of visitors: <span id="visitorCount"></span></p>
localStorage object to store the number of visitors to your website. It also creates a function called
addVisitor() that increments the visitor count and displays it on your web page.
When the page loads, the
window.onload event is triggered, which checks if the
visitorCount key is present in the
localStorage object. If it’s not present, it sets the count to 0. If it’s present, it retrieves the count and updates the display on the web page.
Note that this code only counts the number of visitors to your website using
localStorage, which means the count will reset to 0 if the user clears their browser data or switches to a different device. If you want to track visitors more accurately, you may want to use a more robust analytics tool like Google Analytics.