Visitor Counter

← Back to Portfolio

Website Visitor Count

0

Thank you for visiting our website!

You are visitor number 0.

JavaScript Implementation

This is a JavaScript implementation of a visitor counter that uses localStorage to persist the count between visits. In a real-world scenario, this would typically be implemented using server-side code (like PHP) with a database to store the count.

JavaScript Code

// JavaScript implementation of a visitor counter using localStorage
document.addEventListener('DOMContentLoaded', function() {
    // Get the current count from localStorage or initialize to 0
    let count = localStorage.getItem('visitorCount');
    
    // If count doesn't exist yet, initialize it
    if (count === null) {
        count = 0;
    } else {
        count = parseInt(count);
    }
    
    // Increment the count for this visit
    count++;
    
    // Save the updated count back to localStorage
    localStorage.setItem('visitorCount', count);
    
    // Display the count
    document.getElementById('counter').textContent = count;
    document.getElementById('visitor-number').textContent = count;
});

PHP Version (For Reference)

<?php
// File to store the visitor count
$counterFile = "counter.txt";

// Check if the file exists, create it if it doesn't
if (!file_exists($counterFile)) {
    $handle = fopen($counterFile, "w");
    fwrite($handle, "0");
    fclose($handle);
}

// Read the current count
$handle = fopen($counterFile, "r");
$count = fread($handle, filesize($counterFile));
fclose($handle);

// Increment the count
$count = intval($count) + 1;

// Write the new count back to the file
$handle = fopen($counterFile, "w");
fwrite($handle, $count);
fclose($handle);

// Display the count
echo '<div class="counter-value">' . $count . '</div>';
?>