HTML5 – Local Storage

HTML5 – Local Storage

The HTML5 Web Storage API makes it possible to store data locally, and can store 5M of data, which can be used by a domain at will. Note that it is a domain, which means that the saved data cannot be accessed across domains.

I always like to learn new knowledge in practice, and today is no exception. I used localStorage to make a small note application, and the data is stored in the browser.

How about it, not bad, right? Let's use this example development process to introduce localStorage!

Getting Started

I won’t paste the HTML and CSS code here. If you want to run this example locally, I will provide the source code download link at the end of the article.

First of all, I would like to talk about how to create such a note. The specific process should be as follows.

  1. Get user input
  2. Get the level of the note, which is selected in <select>.
  3. Save the content and rating in an object and convert it to a string using JSON.
  4. Generate a key to save data. For easy search, create an array to store the key separately. Of course, this array is also converted into a string using JSON.
  5. Use the setItem() method of localStorage to save the note object and the key array string.
  6. Adds a tag to the DOM structure.

According to the above process, you can write the following code

  1. function createNote() {
  2. var noteElement = document.getElementById( "note" );
  3. var noteValue = noteElement.value;
  4. noteElement.value = "" ;
  5.  
  6. var levelObj = document.getElementById( "note-level" );
  7. var index = levelObj.selectedIndex;
  8. var level = levelObj[ index ].value;
  9.  
  10. var noteObj = {
  11. "value" : noteValue,
  12. "level" : level  
  13. }
  14.  
  15. var date = new Date ();
  16. var key = "note_" + date .getTime();
  17. localStorage.setItem( key , JSON.stringify(noteObj));
  18.  
  19. var notesArray = getNotesArray();
  20. notesArray.push( key );
  21. localStorage.setItem( "notesArray" , JSON.stringify(notesArray));
  22.  
  23. addNoteToDOM( key , noteObj);
  24. }

It is worth noting that localStorage can only save string values, so we have to use JSON to convert it to a string here. You can use the following code to store an integer or floating point number.

  1. localStorage.setItem( "my_num" ,10);

This line of code does work, that's because JS automatically converts it to a string, so if you want to get an integer out, you have to convert it, like this.

  1. var num = parseInt(localStorage.getItem( "my_num" ));

In the above code, two custom functions are used, namely getNotesArray() and addNoteToDOM(). Their functions can be easily identified by their names. However, it is puzzling why we need to use an array to store keys?

There is one thing you need to know. In a real website, you can't just store notes, right? You also need to store a lot of other data. If you save a lot of other data, then finding notes is a very time-consuming task. Why should I look for notes?

What if your user closes the browser and then reopens the website? At this time, we have to find the notes. Okay, let's take a look at the getNotesArray() function.

  1. function getNotesArray() {
  2. var notesArray = localStorage.getItem( "notesArray" );
  3.  
  4. if (!notesArray) {
  5. notesArray = [];
  6. localStorage.setItem( "notesArray" , JSON.stringify(notesArray));
  7. } else {
  8. notesArray = JSON.parse(notesArray);
  9. }
  10.  
  11. return notesArray;
  12. }

Use localStorage.getItem() to get the array. If the array does not exist, create one and then convert it into a string and save it. If the array already exists, convert it from a string to an array. In short, an array should be returned for us to use.

Okay, now you know what we are talking about. Next is the addNoteToDOM() function. This function is even simpler. Let’s take a look at it.

  1. function addNoteToDOM( key , noteObj) {
  2. var notes = document.getElementById( "note-list" );
  3. var note = document.createElement( "li" );
  4. note.setAttribute( "id" , key );
  5. note.onclick = deleteNote;
  6.  
  7. var value = noteObj.value;
  8. note.innerHTML = value;
  9.  
  10. var level = noteObj.level ;
  11. note.setAttribute( "class" , level );
  12. notes.appendChild(note);
  13. }

First of all, we need to explain that #note-list is a <ul> element, and our notes are also composed of its child elements <li>. The rest is simple. We assign values ​​to <li>, and then add different background colors to it according to the level of the tag. This is achieved by setting a class for it.

It is worth noting that here we pass the key as a parameter, and use the key value to set the id attribute for <li>. This is to achieve the purpose of deletion. After all, we can't just create a tag without knowing how to delete it, so here we also set a click event for <li>.

  1. function deleteNote(e) {
  2. var key = e.target.id;
  3. localStorage.removeItem( key );
  4. var notesArray = getNotesArray();
  5.  
  6. for (var i = 0; i < notesArray.length; i++) {
  7. if ( key === notesArray[i]) {
  8. notesArray.splice(i, 1);
  9. }
  10. }
  11. localStorage.setItem( "notesArray" , JSON.stringify(notesArray));
  12.  
  13. deleteNoteFromDOM( key );
  14. }

When the <li> element is clicked, an event object will be passed in. Through target, we can get the object that triggered the event. We get the id of this object and delete it from the DOM.

But this is not the point. Deleting a tag means that we also need to delete its value from the local storage and remove it from the key array. We use removeItem and splice() to achieve this goal.

expand

We have explained the use of localStorage above, and the code above contains the core code of the note application. It is worth mentioning that there is also a sessionStorage, which is used exactly the same as localStorage, the only difference is that once the browser window is closed, all the saved data will be deleted.

Of course, this is an attribute in HTML5, so we need to detect it when using it. You can use the following code to detect whether the browser supports localStorage.

  1. if (window[ "localStorage" ]) {
  2. // your logic code
  3. }

<<:  In-depth exploration of the essence of Android asynchronous Handler

>>:  Android Studio generates signature files, automatically signs, and obtains SHA1 and MD5 values

Recommend

Can you become a brand by selling goods online?

Topic: "Can online sales become a brand?&quo...

After a brand is bound to a live broadcast room, how to retain traffic?

On October 20, Li Jiaqi and Wei Ya’s live broadca...

Open and Create the Future BYD Global Developers Conference was grandly held

September 5, 2018 is destined to be recorded in t...

I went to Dunhuang to check in and found that Crescent Lake has become "fat"?

Science Times reporter Hu Lijuan With the Nationa...

Why does the Android system use Binder as the IPC mechanism?

The Android system provides a variety of inter-pr...

How much does it cost to apply for a 400 phone number?

How much does it cost to apply for a 400 phone nu...

How to find accurate drainage methods?

There is a cruel fact: the online traffic dividen...

Dialogue on Innovation—51CTO’s first developer competition has started!

/* Live to change the world Here, every work may ...

WatchKit, HealthKit, ApplePay, HomeKit, App Store Review Guide

[[145146]] The WatchKit, HealthKit, ApplePay and ...