January 15, 2002 - Restoring Cookies in Persistent Related Menus | WebReference

January 15, 2002 - Restoring Cookies in Persistent Related Menus

Yehuda Shiran January 15, 2002
Restoring Cookies in Persistent Related Menus
Tips: January 2002

Yehuda Shiran, Ph.D.
Doc JavaScript

One of the problems of related menus is that once you visit another Web page and then come back, the menu selections tend to change. You can overcome this problem with cookies. The cookie property belongs to the document object. Play around with these related menus:

Write down the entries you see on both menus. Let's assume that the left and right menus are level2 and level23, respectively. Now, surf to another Web site of your choice. Hit the browser's Back key. You will see that both menus have retained the entries of .level2 for the left menu and level23 for the right menu.

The trick is to save the menu index in a cookie whenever it changes, and restore the cookie upon the page's reloading. We save the cookie when the right menu ("list") changes, under the name of listSelectedIndex.

We restore the cookie when the page loads. Actually, we need to do more than that. The selected index of the left menu persists by itself, so we need to adjust again the right menu accordingly. If the left menu is level2, for example, the right menu should present the options level21, level22, and level23. The particular option that needs to be selected out of these three is read from the restored cookie.

Let's see how we reflect this business logic in our code. First, we add the onLoad event handler to the <BODY> tag:

<BODY onLoad="refreshOnDocLoad()">
The refreshOnDocLoad() function just calls the relate() function with the first form of the page:

function refreshOnDocLoad() {
  relate(document.forms[0]);
}
The relate() function first initialized the options of the right menu to null:

  var options = form.list.options;
  for (var i = options.length - 1; i > 0; i--) {
    options[i] = null;
  }
Then, it assigns the relevant options from the left menu:

  var curAr = ar[form.topics.selectedIndex];
  for (var j = 0; j 
Now, it reads the cookie:

  var indexOfSelectedOption = getCookie("listSelectedIndex");
We just need to make sure the cookie is not empty. If it is, we select the first option. If it is not empty, we use its contents to pick the selected index:

  if (indexOfSelectedOption != null) {
    options[indexOfSelectedOption].selected = true;
  } else {
      options[0].selected = true;
    }