offer jobs schedule amazon media file explorer download upload index folder image licenses menu widget Play Pause profile-settings more dots-two-horizontal dots-two-vertical more-vertical pending google-plus hangouts facebook instagram whatsapp spotify telegram twitter vine renren rss youtube twitch vimeo flickr dribble behance deviantart 500px steam github soundcloud skype reddit linkedin lastfm delicious stackoverflow pinterest xing flattr foursquare yelp World

Working With The Local & Session Storage In JavaScript

We previously take a deep dive into the Windows Object, Properties, Methods, and even the Document Object itself, in this guide, we would explore working with the local and session storage in JavaScript, which is also part of the Windows Object, so, you might wanna take a look at the previous tutorial to get a better understanding of how things works.

What are localStorage and sessionStorage

The localStorage allows you to access and store a Storage object for the Document's origin. When I say origin, I mean the scheme (protocol), host (domain), and port of the URL used to access it. Two objects have the same origin only when the scheme, host, and port all match.

  • http://example.com/app1/index.htmland http://example.com/app2/index.htmlhave the same origin because scheme (http) and host (example.com) matches.
  • http://Example.com:80and http://example.comhave the same origin because a server delivers HTTP content through port 80 by default, if the first one has another port, it won't have the same origin
  • http://example.com/app1 and https://example.com/app2 have a different origin because the schemes are different (http, https)
  • http://example.com http://www.example.comand http://myapp.example.comall have a different origin because the hosts are different, www. is a host on its own.
  • http://example.comand http://example.com:8080have a different origin because the ports are different.

I hope that clarifies the origin stuff.

Now, a sessionStorage accesses a session Storage object for the current origin.

The difference between a sessionStorage and a localStorage is that a sessionStroage is cleared when the page session ends, while the localStorage doesn't expire, but you can clear it yourself if you wish.

The localStorage works a bit differently in a private or incognito mode, Data in a localStorage object created in a "private browsing" or "incognito" session is cleared when the last "private" tab is closed.

Data stored in localStorage is specific to the protocol of the page. In particular, data stored by a script on a site accessed with HTTP (e.g., http://example.com) is put in a different localStorage object from the same site accessed with HTTPS (e.g., https://example.com ).

If you are familiar with the TinyMCE editor in WordPress, you might not be aware that it autosaves a couple of post edits and other info, see the screenshot below:

WordPress Tinymce localStorage

So, using storage can be really useful in your application.

Storing and retrieving a value in local and session Storage

You can store a value, and you can also retrieve it.

To set a localStorage item, you use key-value, the key is what you want to call the item, and the value is what you are storing.

Here is an example:

// set local storage item
localStorage.setItem('author', 'the_devsrealm_guy');
localStorage.setItem('Language', 'JavaScript');

// set session storage item
sessionStorage.setItem('author', 'the_devsrealm_guy');
sessionStorage.setItem('Language', 'JavaScript');

If I check the application tab, you'll see it is set:

Session and Local Storage Illustration

Now, once I close the browser or the tab of the URL, the sessionStorage would be gone.

To remove an item, you can simply do:

// remove from localStorage
localStorage.removeItem('author');

// remove from sessionStorage
 sessionStorage.removeItem('author');

Cool, so far. we have been setting an item, to get an item, you simply do:

let author, language;
// get from localStorage
author = localStorage.getItem('author');
language = localStorage.getItem('Language');

// Log to localstorage to Console:
console.log('Local Storage: ' + author + ': ' +  language);

// get from localStorage
author = sessionStorage.getItem('author');
language = sessionStorage.getItem('Language');

// Log to sessionstorage to Console:
console.log('Session Storage: ' + author + ': ' +  language);

 Get Session and Local Storage items

To clear all local or session storage, you simply do:

// clear all local storage
 localStorage.clear();

// clear all sessionstorage
 sessionStorage.clear();

Cool.

Storing Input Typed Value in the localStorage

Let's say you want to save whatever you type in an input box to the localStorage, you can easily do this by adding a click event type with a handler that set the item.

Using the following HTML structure:

.............................
.............................
 <div class="content-wrapper text-center">
        <div class="container-fluid">
            <div class="container">
                <div class="row justify-content-center">
                    <div class="col-md-8">
                        <div class="card bg-light">

                            <div class="card-body">
                                <h4 class="card-header">Dashboard</h4>
                                You are logged in!, the_devsrealm_guy
                            </div>
                            <div class="container-fluid">
                                <div class="row justify-content-lg-start">
                                    <div class="col-6 col-sm-5 col-md-4 col-lg-3 m-auto">
                                        <h4>Posts</h4>
                                    </div>

                                    <div class="col-6 col-sm-5 col-md-4 col-lg-3 m-auto">
                                        <div class="form-group">
                                            <label for="task" class="required w-100"></label>
                                            <input type="text" class="form-control " id="task" placeholder="Something"  name="email" value="" autofocus>
                                            <input type="submit" value="Add Task" id = "input" class="btn mt-10 add-task">
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- First row -->
                            <div class="row justify-content-lg-start">
                                <div class="col-12 col-sm-5 col-md-4 col-lg-3">
                                    Almost Done With Our Application
                                </div>
                                <div class="col-6 col-sm-5 col-md-4 col-lg-2 m-5">
                                    <a href="/posts/25/edit" class="btn btn-primary">Edit</a>
                                </div>
                                <div class="col-6 col-sm-5 col-md-4 col-lg-2 m-5">
                                    <a href="/posts/25" target="_blank" rel="noopener" class="btn btn-primary">View Post</a>
                                </div>
                                <div class="col-6 col-sm-5 col-md-4 col-lg-2 m-5">

                                    <form method="POST" action="http://simpleapp.com/posts/25" accept-charset="UTF-8" class="pull-right"><input name="_token" type="hidden" value="Ph2PQpUdxJHuoxUkHb892VfbfR0fuYHY60V2iW5a">
                                        <input name="_method" type="hidden" value="DELETE">
                                        <input class="btn btn-danger" type="submit" value="Delete">
                                    </form>
                                </div>
                            </div>
                            <!-- First row -->
                            <div class="row justify-content-lg-start">
                                <div class="col-12 col-sm-5 col-md-4 col-lg-3">
                                    Test Mastering Plugin New
                                </div>
                                <div class="col-6 col-sm-5 col-md-4 col-lg-2 m-5">
                                    <a href="/posts/26/edit" class="btn btn-primary">Edit</a>
                                </div>
                                <div class="col-6 col-sm-5 col-md-4 col-lg-2 m-5">
                                    <a href="/posts/26" target="_blank" rel="noopener" class="btn btn-primary">View Post</a>
                                </div>
                                <div class="col-6 col-sm-5 col-md-4 col-lg-2 m-5">

                                    <form method="POST" action="http://simpleapp.com/posts/26" accept-charset="UTF-8" class="pull-right"><input name="_token" type="hidden" value="Ph2PQpUdxJHuoxUkHb892VfbfR0fuYHY60V2iW5a">
                                        <input name="_method" type="hidden" value="DELETE">
                                        <input class="btn btn-danger" type="submit" value="Delete">
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

</div>
.............................
.............................

Looks like this:

Examining DOM Page

It'll store the value of whatever the user types in the input into a variable, and once the user clicks the Add Task, it gets saved to the localStorage. Here is how the code looks:

document.querySelector('.form-group').addEventListener('click', storeinput);

function storeinput(e) {
    let tasks; // This variable would hold the user input
    tasks = document.getElementById('task').value // store the value of what user add into the input field to tasks
    localStorage.setItem('name', tasks); // Store the tasks to localstorage
    console.log('Saved To Local Storage');

    e.preventDefault(); // Prevent default behaviour of the element we are working on
}

Adding Multiple Values to one key in a localStorage

You can only have one key at a time, if you try to add multiple values it would replace the value since it thought you are referring to the key. If you want to store multiple key values, you can change the key name to another thing. If you instead want whatever you are storing to get appended to the value, you can create an array of items and store that as a string.

document.querySelector('.form-group').addEventListener('click', storeinput);

function storeinput(e) {

    let values = document.getElementById('task').value // store the value of what user add into the input field to value

    if(localStorage.getItem('name') === null) { // if local storage key name is empty
        val = []; // Set it to an empty array
    } else { // else if name key has a value
        val = JSON.parse(localStorage.getItem('name')); // get what is there, JSON.parse is used to parse the val in the name
    }

    val.push(values); // This would add on to the variable value

    // To Then store it, you can setitem like so:
    localStorage.setItem('name', JSON.stringify(val));

    console.log('Saved To Local Storage');
    e.preventDefault(); // Prevent default behaviour of the element we are working on
}

Let me explain how this works:

First: document.querySelector('.form-group').addEventListener('click', storeinput);

document.querySelector is used to select the div element that has a class of form.group, which is what houses the input box and the submit button, we then added an event listener to listen to a click event type, and once a click is been captured, the event listener passes what should be done to the event handler, which is the storeinput function.

In the storeinput function, I started by setting the value of whatever the user types in the input box into the values variable, here:

let values = document.getElementById('task').value // store the value of what user add into the input field to value

In the if block I checked if the key (in my case, my key is call name) is empty, and if it is empty, I set the valvariable to an empty array, which is different from the values variable which is used to store whatever the user type in the input box, the val variable would be the one to store items in the localStorage.

Moving on, if the if statement is false, that is if there is truly a value in the namekey, if the below is not empty:

Value of the key name is empty

if that value isn't empty, the else block stores whatever is in the key "name" value into the valvariable, here:

val = JSON.parse(localStorage.getItem('name')); 

We can't just get the value, we need to parse it with JSON, and that is because the values or strings should be stored in a JSON format.

Once, we've gotten the value, we use val.push(values) to push whatever is in the values variable (what the user types in the input box) to the val variable, it would append it to the end of what is already in the val variable.

Lastly, to store it in the localStorage we use JSON.stringify to convert a JavaScript object or value to a JSON string, and that is it, easy peasy. Here is an illustration of the end result:

store to localStorage when click event happens in the input box

You'll notice, in the addeventlistener method I set the event type to click event, so, whenever a click happens around the element, the value in the input box stores to the localStorage even empty value get stored as you can see in the illustration.

If you only want to capture the submit button and nothing else, then you must put your child element within a form element with an event type of submit, this way, the value only gets stored whenever a user clicks the submit button, remember, the submit event type would only work in a form element.

If you don't want to use a form element, then you can use an if condition that checks if the user clicks the add task button by finding the className of the button, you then act on that, here is an example of how that would work:

function storeinput(e) {

    let values = document.getElementById('task').value // store the value of what user add into the input field to value

    if (e.target.classList.contains('add-task') ) { // Checks If User clicks the add-task button

        if (localStorage.getItem('name') === null) { // if local storage key name is empty
            val = []; // Set it to an empty array
        } else { // else if name key has a value
            val = JSON.parse(localStorage.getItem('name')); // get what is there, JSON.parse is used to parse the val in the name
        }

        val.push(values); // This would add on to the variable value

        // To Then store it, you can setitem like so:
        localStorage.setItem('name', JSON.stringify(val));

        console.log('Saved To Local Storage');

    }

    document.getElementById('task').value = " "; // Clear the input on each click

    e.preventDefault(); // Prevent default behaviour of the element we are working on
}

I commented on it with: // Checks If User clicks the add-task button

Using Loops To Get The Value from a localStorage

To get the value out from the localStorage, you can either use a forEach, which is an Array method that we can use to execute a function on each item in an array, or you can use for/of loop, you can't use for loop or while loop because they won't know how to get the amount of items in the list.

You can use for/of loop to loop through the key-value like so:

let getval = JSON.parse(localStorage.getItem('name'));
let item;

for(item of getval) {
    console.log(item);
}

and you can use the forEach array method like so:

let getval = JSON.parse(localStorage.getItem('name'));

getval.forEach(function(item){
    console.log(item);
});

They would both give you the same result, but the forEach method is simpler because they are specifically built for Arrays, Maps, and Sets. The way it works is really simple, instead of having to say for(item of getval), the forEach loop would take a callback function. 

The function will be executed for every single element of the array. It must take at least one parameter which represents the elements or item of the array, in our case, we are telling the function to log each element or item in the array getval.

Alternatively, you can shorten the forEach to:

let getval = JSON.parse(localStorage.getItem('name'));

getval.forEach(item => console.log(item));

The same thing but shortened, if you want to get the index of the items, forEach array method takes an optional index parameter that would get you the index of each item:

let getval = JSON.parse(localStorage.getItem('name'));

getval.forEach((item, index) => {
    console.log('Index: ' + index + ' Value: ' + item)
});

5. forEach with index parameter

Cool. That would conclude this guide on local and session storage. Hope you enjoyed it.



Related Post(s)

  • Getting Started With JavaScript (Introduction)

    This is my first JavaScript guide on this blog, and in this guide, we would go over the introduction of JavaScript, but first… What is JavaScript? JavaScript is a client-side scripting language su

  • Operator in Javascript

    Operators in javascript can either be used for logical expression where you connect two or more expressions and can be a comparison expression where you compare two values. You can also use an operat

  • Exploring Data Types, and Variables in JavaScript

    In JavaScript or any programming language, a data type is an attribute of data that tells the interpreter how the programs intend to use the given data. JavaScript support a couple of data type whic

  • Creating a Loader and Remove it After a Specific Time Using JavaScript/CSS/SVG

    In this guide, we would create a loader, and remove it after a specific time using CSS and JavaScript. The icon would be in SVG format, and the rotation would be done in CSS, while the removal after

  • Object Oriented Programming in JavaScript (The ES5 Way)

    In this guide, you'll learn and understand how to create and use Objects in JavaScript (ES5). While ES6 already supports creating classes (which is the way you create objects in Java, PHP, etc), they

  • Guide To Functions In JavaScript

    Functions in JavaScript or any programming languages are modular building blocks for creating powerful and modular scripts, using function makes it easy to isolate a code since it would be packaged u