Using cookies in JavaScript

Using cookies


This JavaScript example places one item from a set of items (tips, thoughts, quotes, banners)
on your Web page. It simply includes in your page one string from a big array.
Since the strings may be long and may contain any HTML tags, you can easily create,
for example, banner rotation.


Each time the page loads, a new item will be displayed.
Every visitor has his own counter stored in a browser cookie.



<html>

<body>



<script type="text/javascript">


<!--

var count=document.cookie.indexOf("cnt=");

if(count>=0) count=document.cookie.substring(count+4);

else count=0;

document.cookie = "cnt=" + (count+1) + ";expires=Fri,1 Jan 2010 00:00:00";

var aStrings = new Array(

"<a href='index.html'>Home Page</a>",


"<a href='examples.html'>JavaScript Examples</a>",

"<a href='tutorials.html'>JavaScript Tutorials</a>"

);

document.write(aStrings[count%aStrings.length]);

//-->


</script>



</body>

</html>

This script uses a cookie (a small file that gets written onto your hard disk by JavaScript
from the Web site you're visiting) to store the variable count.
This variable is incremented every time the page is loaded, and is used as an index of the
array aStrings, which contains HTML strings.

No comments: