JavaScript function that keeps the count of the number of visitors on the website:
Here is a JavaScript function that keeps the count of the number of visitors on the website:
function countVisitors() {
// Check if the 'visitors' key exists in local storage
if (localStorage.getItem('visitors') === null) {
// If the 'visitors' key does not exist, set it to 1
localStorage.setItem('visitors', 1);
} else {
// If the 'visitors' key exists, increment the value by 1
let visitors = parseInt(localStorage.getItem('visitors'));
localStorage.setItem('visitors', visitors + 1);
}
// Get the current value of the 'visitors' key
let visitors = localStorage.getItem('visitors');
// Print the current value of the 'visitors' key to the console
console.log(`Number of visitors: ${visitors}`);
}
This function uses the localStorage API to store the number of visitors in the browser's local storage. The localStorage API allows you to store key-value pairs in the browser, which persist even after the page is refreshed or closed. The localStorage API is supported by all modern browsers, but it is not supported by older browsers.
The countVisitors function checks if the visitors key exists in the local storage. If it does not exist, it sets the value of the visitors key to 1. If it does exist, it increments the value of the visitors key by 1. Finally, it prints the current value of the visitors key to the console.
To use this function, you can call it when the page loads or when the user performs a certain action, such as clicking a button.
// Call the countVisitors function when the page loads
window.onload = countVisitors;
// Call the countVisitors function when the user clicks the button
document.getElementById('my-button').addEventListener('click', countVisitors);
Note that this function only keeps track of the number of visitors on the website in the local storage of the user's browser. It does not keep track of the number of visitors on the server side. If you want to keep track of the number of visitors on the server side
Comments
Post a Comment