• T
  • T

Using localStorage Instead of Cookies

If you need simple access to what cookies give you, localStorage or sessionStorage can be great alternatives. You can set it with something like this in jQuery.

$('#ID').click(function() {
  localStorage.setItem('itemName','itemValue');
});

Then to use the value set, you can get it with

localStorage.getItem('itemName');

That will return the string of ‘itemValue’. With that, you can set it as a class on a div or something similar. Here is one example I recently did.

var storageItem = localStorage.getItem('itemName');
$('#readingFont').addClass(storageItem);

That took the string I set with localStorage, and added it to the div as a class. You can use sessionStorage alternatively to localStorage, if you only want it to be remembered for the duration of that visit for your user. Then next time they restart their browser, it will be cleared.