Toggle

Normally when someone visits a web page more than once they see the same information each time unless you have updated the page in between. This isn't always what you want to occur and doesn't have to be the case provided that you implement something that detects if the person has visited the page before.

The script that we are going to look at here provides us with a simple way of providing two alternatives depending on whether the person has visited the page an odd or even number of times before. Basically the script creates a toggle function that returns true or false based on whether the visit is an odd or an even one.

The simplest way in which we can keep track of return visits by the same visitor is to store information about them in a cookie. For the purpose of this script we simply need to store a zero or one in a cookie for the current page depending on whether this is an odd or even visit. This allows us to comply with any local laws regarding the use of cookies as the bare minimum of information necessary for the functioning of the script is being saved since the existence of the cookie simply tells us that the person has visited the page before and the zero or one contained in the cookie identifies an odd or even visit.

This latest version of the toggle function is written to completely wrap all of the code that it uses to read and write the cookie so as to keep the minimum number of variables in the namespace where you are using the script. Only the toggle() and thisPage() functions can be referenced from your own code with everything else being wrapped inside those functions where it cannot interfere with anything else.

You can of course use the toggle() function by itself without using the thisPage() function if your toggling requirements are not related to a specific web page. All that you need to do is to make sure that you pass a value for the cookie name you want to use to track this particular toggling activity as the first parameter to the toggle() and an expiry date for the cookie as the second parameter (if you pass zero as the expiry then the script defaults to one day). If the person doesn't visit again before the cookie expires then their next visit will start over again as if it were their first while if they do visit again then the expiry date can/will be extended based on the current visit time.

JavaScript

 

This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow
Donate