- To test if localStorage or sessionStorage is available on our browser, we can use the following code:
(function() { if (typeof sessionStorage != 'undefined') // or if (window['localStorage'] !== null) // or using the ModernizR library if (Modernizr.localstorage) })();
- Let's use the getItem(key) method:
var color = localStorage.getItem('white'); var color = localStorage['white']; var color = localStorage.white;
- Now let's use the setItem(key, value) method to store data in the localStorage object:
localStorage.setItem('name', $('#name').val()); localStorage['name'] = $('#name').val(); localStorage.name = $('#name').val();
- Next, we will store a complex object in the localStorage:
var colors = { white: '#000', black: ...