Make an active site

Storing data on the local machine

When you show everyone your adjustable clock, they are very impressed—for a while. Then, they complain that the clock doesn’t remember the entered offset. Each time the clock web page is opened, the minutesOffset is zero, and the clock shows the correct time. They want a clock that retains the minutesOffset value so that each time it is started, it has the same offset that they set last time it was used. They assumed you would know that was what they wanted, and now you must provide it.

read.jpg

JavaScript allows web pages to store data on a local machine. It works because the browser has access to the file storage on the host PC, and the browser can write small amounts of data into this storage and recover it when requested.

Below, the storeMinutesOffset function shows how we can use this feature from a JavaScript program. The storeMinutesOffset function accepts a parameter called offset, which holds the offset value to be stored in the browser’s local storage. The value is stored by the setItem method provided by the localStorage object. This method accepts two arguments—the name of the storage location and the string to be stored there.

function storeMinutesOffset(offset){
  localStorage.setItem("minutesOffset", String(offset));
}

The loadMinutesOffset function below fetches a stored offset value using the getItem method, which is provided by the localStorage object. The getItem method is supplied with a string that identifies the local storage item to return. If there is no item in the local storage with the given name, getItem returns null. We’ve seen null before. It is a value that means “I can’t find it.” The code below tests for a return value of null from the getItem function and sets the offset to 0 if this happens. This behavior is required because the first time the clock is loaded into the browser, there will be nothing in local storage.

You can find this code in the example Ch03-04_Storing_Adjustable_Clock.

read.jpg