NOTE: In this article, just like in my previous ones, I will be utilizing jQuery and jQuery-json plugin.
HTML:
<input type="button" id="btnLeavePage" value="Go To Another Page" /> <br /> <a id="lnkToggleDisplay" href="#">Show/Hide</a> <br /> <div id="controlDiv"> <br /> <input id="txtInput" type="text" /> <select id="sltInput"> <option value="1">First</option> <option value="2">Second</option> <option value="3">Third</option> </select> </div>
Simple enough. I got a button which navigates to a different page (supposedly loosing all client information about the page), a div with an input text and a select , and a link which toggles the display of the div.
JavaScript:
I will not explain the essentials of cookies. If you would like to learn more about managing cookies with JavaScript, here is a great article on Quirksmode: JavaScript - cookies.
function WriteCookie() {
var pageState = {
'text': $('#txtInput').val(),
'select': $('#sltInput').val(),
'toggle': $('#controlDiv').is(':visible')
};
var date = new Date();
date.setTime(date.getTime() + 3*1000);
document.cookie = 'PageState=' + $.toJSON(pageState) + ';expires=' + date.toGMTString() + '; path=/';
}I need to save the controls state to the cookie. What format should I use for it? I was first thinking about custom delimiters. You know, throw in a '|' or a '~' in between the controls data and then just use JavaScript’s split function when parsing it out. This approach works in cases where the user is limited to a certain input. In my case, there is an input text without any validation attached to it, thus if a user types in my secret delimiter, I’m basically screwed… Here is where the idea of using JSON object came to my mind. I tried it out and it worked very well. In the code above, I’m constructing the JSON object with 3 values that hold my page’s state: the value of the input text, the value of the select control, and the status of the div (shown or hidden). I then convert my JSON object to a JSON string, since the cookie data is in string format. For the purpose of this demo, I’m setting the cookie to expire in 3 minutes.function ReadCookie() {
var cookies = document.cookie.split(';');
for (i in cookies) {
if (cookies[i].indexOf('PageState') == 0) {
var pageState = $.evalJSON(cookies[i].substring(10));
$('#txtInput').val(pageState['text']);
$('#sltInput').val(pageState['select']);
(pageState['toggle']) ? $('#controlDiv').show() : $('#controlDiv').hide();
}
}
}To read the cookie I perform pretty much the standard JavaScript logic: split the cookie data, find my cookie and, if found, do stuff with it. I grab the JSON string out of the cookie data and evaluate it into a JSON object. Once the object is ready, I set my page controls to the data inside the object. Of course, jQuery is making it quick and simple here.Putting JavaScript together:
$(document).ready(function() {
$('#lnkToggleDisplay').click(function() {
$('#controlDiv').is(':visible') ? $('#controlDiv').hide() : $('#controlDiv').show();
});
ReadCookie();
$('#btnLeavePage').click(function() {
WriteCookie();
window.location = "navigate_to_page.htm";
});
});On document ready, I first assign click handler to the toggle link. This changes the visibility of the div holding the two HTML controls. Then I call ReadCookie() function to set page elements’ values. At last, I assign click handler to the navigation button. Notice that it’s on navigation, when the user is leaving the page, the page state is written to the cookie. You may check out the working example.Conclusion:
Once again, the usage of cookies is not appropriate in every case. As for the problem that I was facing, this solution was simple and neat, did not take long time to implement and in fact works very well at the moment. I hope this helps someone.