gola
gola

Reputation: 33

How can I count the number of the visitors on my website using JavaScript?

I need a counter to integrate inside my HTML code that counts from one to three when the visitors visited my webpage.

For example if the first visitor visited my page it count to 1, then the next visitor visited the page it count to 2, and for the 3rd visitor count to 3, then for the 4th visitor again starts from 1 and so on.

Upvotes: 3

Views: 30250

Answers (2)

Goddard
Goddard

Reputation: 3059

You could use a cookie and simply update the cookie count detected when the user refreshes, or with a timer. You could also do different things once you have the cookie. You could also take advantage of localstorage.

Check out - http://samy.pl/evercookie/

<script type="text/javascript" src="evercookie.js"></script>

<script>
var ec = new evercookie(); 

// set a cookie "id" to "12345"
// usage: ec.set(key, value)
ec.set("id", "12345"); 

// retrieve a cookie called "id" (simply)
ec.get("id", function(value) { alert("Cookie value is " + value) }); 

// or use a more advanced callback function for getting our cookie
// the cookie value is the first param
// an object containing the different storage methods
// and returned cookie values is the second parameter
function getCookie(best_candidate, all_candidates)
{
    alert("The retrieved cookie is: " + best_candidate + "\n" +
        "You can see what each storage mechanism returned " +
        "by looping through the all_candidates object.");

    for (var item in all_candidates)
        document.write("Storage mechanism " + item +
            " returned: " + all_candidates[item] + "<br>");
}
ec.get("id", getCookie); 

// we look for "candidates" based off the number of "cookies" that
// come back matching since it's possible for mismatching cookies.
// the best candidate is most likely the correct one
</script> 

Upvotes: 2

Anthony Hilyard
Anthony Hilyard

Reputation: 1240

As indicated in the comments, if you are just looking for some method of loading random pages with equal probability, without more complicated server-side code, you could do something like this:

<script type="text/javascript">
    window.onload = function() {
        var numberOfPages = 3;
        var num = Math.round(Math.random() * numberOfPages);
        window.location.href = "/" + num + ".html";
    };    
</script>

Of course, then you would have pages 0.html, 1.html, and 2.html. This will randomly load one of these three pages with equal probability. It can also be extended to as many pages as you wish, just add more pages and increase the numberOfPages variable. This should work if you put this script within your site's index--the rest of the page can be empty.

Upvotes: 0

Related Questions