Home arrow HTML arrow Page 2 - Building a Visitor Counter in HTML5
HTML

Building a Visitor Counter in HTML5


In this eighth part of the series, I demonstrate how the “localStorage” object's functionality can be used to implement a simple, highly-customizable visitor counter. Although the counter as created here hardly competes with those created with a server-side programming language, it does give you a concrete scenario in which this object can be employed in a more helpful and realistic manner.

Author Info:
By: Alejandro Gervasio
Rating: 5 stars5 stars5 stars5 stars5 stars / 8
January 26, 2011
TABLE OF CONTENTS:
  1. · Building a Visitor Counter in HTML5
  2. · Implementing a client-side visitor counter

print this article
SEARCH DEVARTICLES

Building a Visitor Counter in HTML5 - Implementing a client-side visitor counter
(Page 2 of 2 )

Frankly speaking, the implementation of a visitor counter with the local storage is a process that doesn’t differ too much from building one using a server-side language, as in both cases the underlying logic is nearly the same.

In this particular case, however, the program responsible for making the counter work properly will be encapsulated within a single JavaScript function. This function, not surprisingly called “displayCounter(),” has the following source code:

function displayCounter() {
    // check if the localStorage object is supported by the browser
    if ('localStorage' in window && window['localStorage'] !== null) {
        // if the counter has been defined, increment its value, // otherwise, set it to 0
        ('counter' in localStorage && localStorage['counter'] !== null) ? localStorage['counter']++ : localStorage['counter'] = 0;
        var container = document.getElementById('container');
        if (!container){return};
        // display the counter on screen
        container.innerHTML = 'Hey, you visited this page ' + localStorage['counter'] + ' times.';
    }
}
// call the 'displayCounter()' function when the web page is loaded
window.onload = function() {
    displayCounter();
}

Even though the above function has been widely commented, it’s worth spending a few moments analyzing what it does. The function begins by checking to see if a “counter” property has been defined in the local storage, and if it is not null. If the property exits, then its value is incremented; otherwise, it’s set to 0.

Finally, this value is embedded into a generic div identified as “container,” which for the sake of brevity has been hard coded on the corresponding web page (it’s possible to use some DOM methods and create it on the fly, though). To assure that the counter will be correctly displayed on screen, the function is called after the pertinent page finishes loading, which doesn’t bear any further explanation.

Well, if you ever thought that building a client-side visit counter was a complex task, the implementation of the previous function should make you change your mind quickly. However, to see this sample counter in action, the function must be tied to an HTML5 document.

This will be done below.

The counter in action: adding the function to an HTML5 document

If you’re eager to see if the earlier counter really works as expected, here’s a web page that includes the previous “displayCounter()” function and invokes it after the entire DOM has been parsed:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Client-side visit counter using HTML5 local Storage</title>
<script type="text/javascript">
// implementing a simple client-side visit counter
function displayCounter() {
    // check if the localStorage object is supported by the browser
    if ('localStorage' in window && window['localStorage'] !== null) {
        // if the counter has been defined, increment its value, // otherwise, set it to 0
        ('counter' in localStorage && localStorage['counter'] !== null) ? localStorage['counter']++ : localStorage['counter'] = 0;
        var container = document.getElementById('container');
        if (!container){return};
        // display the counter on screen
        container.innerHTML = 'Hey, you visited this page ' + localStorage['counter'] + ' times.';
    }
}
// call the 'displayCounter()' function when the web page is loaded
window.onload = function() {
    displayCounter();
}
</script>
<style type="text/css">
body {
    padding: 0;
    margin: 0;
    background: #ccc;
    font: 0.8em Arial, Helvetica, sans-serif;
    color: #000;
}
p {
    margin: 0 0 10px 0;
}
#wrapper {
    width: 960px;
    margin: 0 auto;
    background: #fff;
}
#header, #content, #footer {
    padding: 20px;
}
#footer #container {
    font-weight: bold;
    font-size: 1.5em;
    color: #00f;
}
</style>
</head>
<body>
<div id="wrapper">
    <div id="header">
        <header>
            <h1>HTML5 Storage</h1>
            <section>
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
            </section>
        </header>
    </div>
    <div id="content">
        <h2>This is the main content section</h2>
        <section>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
        </section>
        <section>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
        </section>
    </div>
    <div id="footer">
        <footer>
            <section>
                <div id="container"></div>
            </section>
        </footer>
    </div>
</div>
</body>
</html>
Done. At this point, it’s time to give the counter a try and see how it works. So, first of all, make sure that you have at least one tab open in your browser. Done? Good. Now open a new one and run the earlier web page several times (you can even close its tab if you want to do so). After repeating this process for a while, you should get an output similar to the one depicted in the following image: 

There you have it. Thanks to the functionality provided by the local storage, it’s possible to build a functional client-side visitor counter in a snap, without the struggle of using sessions in the web server.

Of course, this simplicity comes with a cost. The counter will stop working if you close the browser’s windows (although IE8+ will keep the data available, as long as you don’t clear its cache). Anyway, if you want to provide visitors to your web site with this little addendum, they’ll surely be more than pleased. So, go ahead and start tweaking this sample counter! It’ll be a fun experience, believe me.

Final thoughts

In this eighth chapter of the series, things became more interesting, as I demonstrated how the functionality brought by the “localStorage” object can be used to implement a simple, highly-customizable visitor counter. Although the counter in its current version doesn't compete strongly with those created with a server-side programming language, it does illustrate a concrete scenario where this object can be employed in a more helpful and realistic manner.

While it’s valid to stress that there are many other situations where it’s possible to make use of the object, one that shows all of its splendor occurs when saving the state of a graphical user interface. Based on this idea, in the penultimate installment of this series, I’ll be creating a small JavaScript application. It will “autosave,” in the local storage, the data entered into an HTML form at a predefined time interval. This is pretty similar to a feature that can be found in many desktop applications.

Want to see how this form autosaver will be built in a few easy steps? Then don’t miss the next part!


DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

blog comments powered by Disqus
HTML ARTICLES

- Does HTML5 Need a Main Element?
- Revisiting the HTML5 vs. Native Debate
- HTML5: Not for Phone Apps?
- HTML5 or Native?
- Job Hunting? Freelancer.com Lists This Quart...
- HTML5 in the News
- Report: HTML5 Mobile Performance Lags
- The Top HTML5 Audio Players
- Top HTML5 Video Tutorials
- HTML5: Reasons to Learn and Use It
- More of the Top Tutorials for HTML5 Forms
- MobileAppWizard Releases HTML5 App Builder
- HTML5 Boilerplate: Working with jQuery and M...
- HTML5 Boilerplate Introduction
- New API Platform for HTML5

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2018 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials