Getting Started with JavaScript Cookie Tracking
When a visitor lands on a page, you can instantly learn how many times they’ve been there by storing a small piece of data in the browser – a cookie. JavaScript makes this straightforward. The core of the technique lives in a handful of lines that you copy from a demo page, tweak one value that tells the cookie how long to stick around, and drop the whole snippet into the <head> section of your pages. Once in place, the script automatically creates, reads, and updates the cookie whenever the page loads.
The demo code you can find at http://willmaster.com/a/6/pl.pl?art69 is intentionally simple. Lines 6 through 54 hold the engine that manages the cookie. Inside that block, a single variable called DaysToLive controls the cookie’s lifespan. If you want the count to reset after a week, set it to ; for a month, use . Everything else stays the same. Just copy and paste the entire block into your own <head> tag and you’re ready to read visitor counts.
With the cookie engine in place, the script offers two functions: SetCookie(name, value, days) and GetCookie(name). The first writes a name/value pair that survives across page loads, while the second retrieves the stored value. If the cookie is missing or the browser blocks cookies, GetCookie returns an empty string, so the script never crashes.
Below the cookie code sits a small utility that demonstrates how the visitor count is calculated. The key line is:
When a page loads, this line fetches the value stored under the cookie called page_name and assigns it to the visits variable. On the first load, the cookie does not exist, so visits becomes . Each subsequent load increments the stored number by one. If the visitor disables cookies, the count will stay at forever because the browser never writes a new value back to the cookie store.
Deciding on the cookie’s name matters when you use the script across multiple pages. If every page uses the same name, you’ll see a single, cumulative count that reflects the total number of visits across the entire site. If each page gets its own unique name, you’ll see a page‑specific count that only tracks visits to that particular page. Many developers create a master cookie for the entire site and then separate cookies for key sections like the home page or a product catalog. That gives you both an overall view and granular detail.
When you set a cookie name, keep it simple. Alphanumeric characters and underscores are safe; avoid spaces and punctuation. For instance, main_page_visits or product_view_count are good choices. The name you pick will show up in the browser’s cookie list, so pick something that makes sense for future debugging.
Once the counting logic is in place, the next step is to make the data useful. You can use the visits variable to decide whether to show a welcome message, a discount popup, or a tailored call‑to‑action. The code that follows the cookie logic in the demo page is a simple illustration of that idea. It uses conditional statements to display different headings based on the current visit number. The script runs instantly as the page loads, so visitors see a personalized welcome the moment they arrive.
Because the script is pure JavaScript, it works in all major browsers – Chrome, Firefox, Edge, Safari – as long as cookies are enabled. If you need to support older browsers that don’t understand var or string concatenation, consider wrapping the code in a feature detection block or using a lightweight polyfill. In most cases, the code will run out of the box without modification.
Testing the cookie logic is a good practice before you roll it out. Open the console in your browser’s developer tools, clear the existing cookies for your domain, and then reload the page several times. Watch how the visits variable changes, and verify that the content updates accordingly. If the count stays stuck at , check that the cookie name matches exactly and that the DaysToLive value is a positive number.
When the script is behaving as expected, you’re ready to add more sophisticated behaviors. The next section walks through how to tie the visitor count to pop‑up windows, page content, and even custom JavaScript functions. These tricks turn a simple counter into a powerful engagement tool that keeps visitors coming back.
Customizing Content and Popups Based on Visit Count
Once you have a reliable visits variable, you can use it as the basis for dynamic content. The demo page already shows a simple pattern: different headings for the first, second, and subsequent visits. You can copy that approach and replace the document.write calls with any code you need – from injecting a banner to loading an iframe or initiating an AJAX request.
The core idea is the same across all use cases: check the value of visits, then run the code you want. For example, a common pattern is to show a welcome banner on the first visit, a special offer on the third visit, and a loyalty message after the ninth. The conditions look like this:
Because document.write replaces the entire document if called after the page has loaded, you might prefer to manipulate the DOM instead. For instance, you could create a <div id="welcome"> in your HTML and then use JavaScript to set its innerHTML. That approach keeps the page intact and avoids flicker.
When you move beyond headings, pop‑up windows become an attractive option. The demo script includes a Popup(url, width, height) function that opens a new browser window with the specified dimensions. By tying this function to the visitor count, you can deliver targeted content in a separate frame. The code below shows how to launch different pop‑ups for the first, second, and fifteenth visits:
In practice, you’ll want to replace the placeholder URLs with pages that contain the message you wish to display – a welcome video, a discount coupon, or a newsletter signup. Adjust the dimensions to suit the content. A smaller window can hold a quick message, while a larger one can showcase a full‑page feature.
Pop‑ups can be intrusive, so consider adding a close button or making them dismissible after the user has seen them. You can store a secondary cookie that flags whether the user has already viewed a particular popup, preventing it from appearing again on future visits. For example, after the first visit, set a cookie named first_popup_seen to . Then, before calling Popup, check that cookie and skip the window if it’s already set.
Another powerful use of the visits variable is to call completely custom JavaScript functions. Suppose you have a survey that you want to trigger only after the user has returned three times. You could write a runSurvey() function and invoke it like this:
Because the code runs on each page load, you can place the script in a common header file that every page on your site imports. That way, the visitor count logic stays consistent, and you don’t have to duplicate the same code across dozens of pages.
Testing these conditional displays is essential. Use the browser console to log the visits value at different points in the script. Verify that pop‑ups only appear when intended, and that the content changes correctly as the counter increases. If you find that pop‑ups appear too early, double‑check that the Popup function is defined before the conditional block runs.
Remember that not all browsers allow pop‑ups by default. Some will block them unless the user explicitly permits pop‑ups from your domain. To mitigate this, design the pop‑up content to be a non‑intrusive overlay within the page instead. Modern JavaScript libraries let you create modal dialogs that behave like pop‑ups but stay within the same browser window, improving user experience while still delivering targeted messages.
When you’re comfortable with simple conditions, you can build more complex logic. For example, you might store the timestamp of the first visit and calculate how many days the user has been returning. Using Date.now() you can create a “returning visitor” badge that only shows if the visitor is back after a week. Combining time‑based and count‑based criteria gives you a richer understanding of user engagement.
In short, the visits variable is a lightweight tool that opens up a range of personalization possibilities. By pairing it with small functions, modal dialogs, or full page rewrites, you can craft experiences that evolve with each user interaction. The result is a site that feels responsive, rewards loyalty, and keeps visitors coming back for more.





No comments yet. Be the first to comment!