1. Home
  2. Computing & Technology
  3. JavaScript

Toggle Action Cookie Script

1. Introduction and Sample

Join the Discussion

Questions? Comments?

More of this Feature

Get the Script

Normally a web page performs the same Javascript processing every time anyone visits the page. If you want the page to behave differently for different visits by the same person then you need to use cookies to keep track of the number of times that the particular person has visited the page.

Let's suppose that you want to set up your page to act in two different ways and you want your visitors to see the two different behaviours of the page on alternate visits. To do this we need to set a cookie that keeps trac k of whether the person has visited the page an odd or an even number of times and then process accordingly.

This script performs the actual toggle processing for you by creating a cookie named after the page and then saving a value of '0' or '1' in the cookie depending on whether it is an odd or an even numbered visit. By default the script retains the cookie for one day from when it was last set meaning that providecd the person visits the page at least once per day the script will toggle between the two alternate actions. Once sufficient time passes after the last visit for the cookie to expire the page will start over again as if the person hadn't visited before. You can change the time that the cookie is retaiined by setting your own expiry date in the second parameter passed to the toggle function if you need to have the cookie retained for more than one day however in most cases if it is over a day since they last visited your visitor wont remember which of the two behaviours occured on their last visit anyway.

Because the script defaults to using the page name as the name for the cookie you can set up multiple pages that use the same script to toggle behaviour independently of one another (subject to the 20 cookie per site limit). Alternatively you could change the value passed in as the first paramater to the toggle function in order to share the toggle between multiple pages.

If this is what you need to be able to do on your page then the next step is to obtain the script.

Sample Page | Obtain the Script
Explore JavaScript
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. JavaScript

©2009 About.com, a part of The New York Times Company.

All rights reserved.