Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

local storage javascript

function createItem() {
	localStorage.setItem('nameOfItem', 'value'); 
} 
createItem() // Creates a item named 'nameOfItem' and stores a value of 'value'

function getValue() {
	return localStorage.getItem('nameOfItem');  
} // Gets the value of 'nameOfItem' and returns it
console.log(getValue()); //'value';
Comment

localstorage javascript

localStorage.setItem('user_name', 'Rohit'); //store a key/value
var retrievedUsername = localStorage.getItem('user_name'); //retrieve the key
Comment

JS localstorage

> Add item
localStorage.setItem('foo', 'bar');
> Get item
localStorage.getItem('foo');
> Remote item
localStorage.removeItem('foo');
> Clear all
localStorage.clear();
Comment

localStorage

// localStorage for objects, arrays or any data type
var obj = {
	firstName: "Bob",
    lastName: "Jeff",
    age: 13
}
localStorage.setItem("itemname", JSON.stringify(obj)); // Save the obj as string
var item = JSON.parse(localStorage.getItem("itemname")); 
// ^^ Parse string then set `item` as the obj
Comment

local storage

function setItem(name, value) {
  localStorage.setItem(name, value);
}
function getItem(name) {
  localStorage.getItem(name);
}
function deletItem(name) {
  localStorage.removeItem(name);
}
function clearStorage() {
  localStorage.clear();
}
Comment

javascript localstorage

localStorage.setItem("user_name", "Bob");

document.body.addEventListener("click", function(){
  alert(localStorage.getItem("user_name"))
});
Comment

localstorage javascript

localStorage.setItem(key, val);
var val = localStorage.getItem(key);
localStorage.removeItem(key);
localStorage.clear();
Comment

localstorage in js

// Check browser support
if (typeof(Storage) !== "undefined") {
  // Store
  localStorage.setItem("lastname", "Smith");
  // Retrieve
  document.getElementById("result").innerHTML = localStorage.getItem("lastname");
} else {
  document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
Comment

localstorage

localStorage.setItem('Items' , 'Bread');
let Bread = localStorage.getItem('Items');
Comment

localstorage

localStorage.setItem('name', 'Bob') // make/set a key/value
var username = localStorage.getItem('name') // get the key
console.log(username) // log the key
// This data will be saved even after you close the page
Comment

js localstorage

//-----------------------------------------------------------------
//Set
localStorage.setItem('key', 'value');
/*example*/	localStorage.setItem('name', 'Yeasin Ahammed Apon');
//----------------------------------------------------------------
//Get
localStorage.getItem('key');
/*example*/	localStorage.getItem('name');
//------------------------------------------------------------------
//Remove one
localStorage.removeItem('key');
/*example*/	localStorage.removeItem('name');
//-------------------------------------------------------------------
// Remove all
localStorage.clear();
Comment

local storage

As the answers here already talk about the coding aspect. I will talk about
the concept.
Local storage is basically an object stored in the specific browser you are 
using in that moment. And thus it is tied to that browser in that device. It's 
duration is infinite so it never expires

If you only want to store data that only lasts for that browser session(
starts when you open a window and ends when you close it) then the best choice
is sessionStorage
Comment

localStorage

         function saveList() {
           localStorage.storedList = document.getElementById("list").innerHTML;
         }
         //This is a saved list
Comment

localstorage

const { NodeDiskStorage } = require('node-disk-storage')
const nds = new NodeDiskStorage()

/**
 * @description set data
 */

;(async () => {
	await nds.set('user', [
		{
			id: 1,
			name: 'Leanne Graham',
			username: 'Bret',
			email: 'Sincere@april.biz',
			address: {
				street: 'Kulas Light',
				suite: 'Apt. 556',
				city: 'Gwenborough',
				zipcode: '92998-3874',
				geo: {
					lat: '-37.3159',
					lng: '81.1496'
				}
			},
			phone: '1-770-736-8031 x56442',
			website: 'hildegard.org',
			company: {
				name: 'Romaguera-Crona',
				catchPhrase: 'Multi-layered client-server neural-net',
				bs: 'harness real-time e-markets'
			}
		},
		{
			id: 2,
			name: 'Ervin Howell',
			username: 'Antonette',
			email: 'Shanna@melissa.tv',
			address: {
				street: 'Victor Plains',
				suite: 'Suite 879',
				city: 'Wisokyburgh',
				zipcode: '90566-7771',
				geo: {
					lat: '-43.9509',
					lng: '-34.4618'
				}
			},
			phone: '010-692-6593 x09125',
			website: 'anastasia.net',
			company: {
				name: 'Deckow-Crist',
				catchPhrase: 'Proactive didactic contingency',
				bs: 'synergize scalable supply-chains'
			}
		},
		{
			id: 3,
			name: 'Clementine Bauch',
			username: 'Samantha',
			email: 'Nathan@yesenia.net',
			address: {
				street: 'Douglas Extension',
				suite: 'Suite 847',
				city: 'McKenziehaven',
				zipcode: '59590-4157',
				geo: {
					lat: '-68.6102',
					lng: '-47.0653'
				}
			},
			phone: '1-463-123-4447',
			website: 'ramiro.info',
			company: {
				name: 'Romaguera-Jacobson',
				catchPhrase: 'Face to face bifurcated interface',
				bs: 'e-enable strategic applications'
			}
		},
		{
			id: 4,
			name: 'Patricia Lebsack',
			username: 'Karianne',
			email: 'Julianne.OConner@kory.org',
			address: {
				street: 'Hoeger Mall',
				suite: 'Apt. 692',
				city: 'South Elvis',
				zipcode: '53919-4257',
				geo: {
					lat: '29.4572',
					lng: '-164.2990'
				}
			},
			phone: '493-170-9623 x156',
			website: 'kale.biz',
			company: {
				name: 'Robel-Corkery',
				catchPhrase: 'Multi-tiered zero tolerance productivity',
				bs: 'transition cutting-edge web services'
			}
		},
		{
			id: 5,
			name: 'Chelsey Dietrich',
			username: 'Kamren',
			email: 'Lucio_Hettinger@annie.ca',
			address: {
				street: 'Skiles Walks',
				suite: 'Suite 351',
				city: 'Roscoeview',
				zipcode: '33263',
				geo: {
					lat: '-31.8129',
					lng: '62.5342'
				}
			},
			phone: '(254)954-1289',
			website: 'demarco.info',
			company: {
				name: 'Keebler LLC',
				catchPhrase: 'User-centric fault-tolerant solution',
				bs: 'revolutionize end-to-end systems'
			}
		}
	])
	await nds.set('name', 'john doe')
	await nds.set('days', ['senin', 'selasa', 'rabu', 'kamis'])
})()

/**
 * @description get data
 */
;(async () => {
	const getUser = await nds.get('user')
	console.log(getUser)

	const getName = await nds.get('name')
	console.log(getName)

	const getDays = await nds.get('days')
	console.log(getDays)

	console.log((await nds.keys()).length)

	console.log(await nds.clear())
})()
Comment

localstorage api

localStorage //to see localStorage data
localStorage.clear() // to clear all the localStorage data
localStorage.setItem("something") // to set a localStorage Item
localStorage.getItem("something") //to read the localStorage data
localStorage.removeItem("something") // to remove the localStorage data
Comment

javascript localstorage

var KeyName = window.localStorage.key(index);
Comment

localStorage

#you must first stringify it with the JSON.stringify() function

localStorage.setItem('items', JSON.stringify(items));
const x = JSON.parse(localStorage.getItem('items'))
Comment

localstorage syntax

localStorage.setItem('person', JSON.stringify(person)); //stringify object and store
var retrievedPerson = JSON.parse(localStorage.getItem('person')); //retrieve the object
Comment

local storage

localStorage.setItem('localStorage', 1);
Comment

local storage

<form action="2.html" onsubmit="callme()">
    <p>Enter your name</p>
    <input id="tbName" type="text">
    <button type="submit" value="submit">Submit</button>
</form>
<script>
    function callme(){
        var name = document.getElementById('tbName').value;
        sessionStorage.setItem('userName', name);
    }
</script>
Comment

localstorage in javascript

//localStorage contain key value.
//we can get all localStorage from localStorage tab of storage pannel in inspect.
localStorage.setItem("todo","Feed the cat") //set localStorage with key todo and fee the cat as value
localStorage.clear();// clear the localStorage.
//getting localStorage.
const user = localStorage.getItem('user'); //in parameter we send key value

//adding array and object in localStorage.
//when we use tradition way we get string instead of array and object.
//this issues can be remove by using JSON.stringify and JSON.parse.
const todoList= ["Feed the cat","wash"]
localStorage.setItem("todos",JSON.stringify(todoList)); //changing array to string with []
const retrieved= JSON.parse(localStorage.getItem("todos")); // changing string to object.
Comment

localstorage

    import { Injectable, OnDestroy } from '@angular/core';
    import { Subject } from 'rxjs/Subject';
    import { share } from 'rxjs/operators';
    
    @Injectable()
    export class StorageService implements OnDestroy {
      private onSubject = new Subject<{ key: string, value: any }>();
      public changes = this.onSubject.asObservable().pipe(share());
    
      constructor() {
        this.start();
      }
    
      ngOnDestroy() {
        this.stop();
      }
    
      public getStorage() {
        let s = [];
        for (let i = 0; i < localStorage.length; i++) {
          s.push({
            key: localStorage.key(i),
            value: JSON.parse(localStorage.getItem(localStorage.key(i)))
          });
        }
        return s;
      }
    
      public store(key: string, data: any): void {
        localStorage.setItem(key, JSON.stringify(data));
        this.onSubject.next({ key: key, value: data})
      }
    
      public clear(key) {
        localStorage.removeItem(key);
        this.onSubject.next({ key: key, value: null });
      }
    
    
      private start(): void {
        window.addEventListener("storage", this.storageEventListener.bind(this));
      }
    
      private storageEventListener(event: StorageEvent) {
        if (event.storageArea == localStorage) {
          let v;
          try { v = JSON.parse(event.newValue); }
          catch (e) { v = event.newValue; }
          this.onSubject.next({ key: event.key, value: v });
        }
      }
    
      private stop(): void {
        window.removeEventListener("storage", this.storageEventListener.bind(this));
        this.onSubject.complete();
      }
    }
Comment

localstorage

localStorage.removeItem('myCat');
Comment

local storage

window.localStorage.setItem("grade","One");
//in this case, the `grade` is the key while `One` is the value.
Comment

Local Storage

<script>
  //an immediately invoked function that checks to see if the text is in local storage already
  (function(){
    //if the text is in local storage, set the html
    if (localStorage.currentTotal){
    console.log(localStorage.currentTotal);
    document.getElementById('class').innerHTML = localStorage.getItem("currentTotal");
  }
    })();
  //function that gets called for an onclick event
  function myFunction() {
// Store in local storage
localStorage.setItem("currentTotal", "Class current balance total");
//set the inner html to what is in local storage
document.getElementById("class").innerHTML = localStorage.getItem("currentTotal");

}
</script>
Comment

local storage

var answer = localStorage.key(1);
// this statement will retrieve the value of the second item in localStorage.
Comment

local storage

window.localStorage.getItem("key");
Comment

PREVIOUS NEXT
Code Example
Javascript :: js spread exclude property 
Javascript :: ecmascript 7 getmonth as 2 digits 
Javascript :: count duplicate elements in array javascript 
Javascript :: compose javascript 
Javascript :: react native text span 
Javascript :: react include a polyfill webpack v5 
Javascript :: on scroll change navbar color 
Javascript :: remove # url vuejs 
Javascript :: write to console using jQuery 
Javascript :: regExp numero français 
Javascript :: js sort numbers descending order 
Javascript :: prevent form submission on onsubmit function calls 
Javascript :: moment format a date into different format 
Javascript :: Vuejs watch for nested data 
Javascript :: get url params in express 
Javascript :: how to move an element of an array in javascript 
Javascript :: curl post json object command 
Javascript :: usestate remove from array 
Javascript :: out of memory gc overhead limit exceeded. react native 
Javascript :: Axios FormData / not JSON 
Javascript :: how to use br tag in javascript string 
Javascript :: jQuery on right mouse click 
Javascript :: invert binary tree javascript 
Javascript :: css and js on flask 
Javascript :: access to static file nodejs 
Javascript :: all javascript pattern programs 
Javascript :: jquery scrollheight 
Javascript :: react copy to clipboard button 
Javascript :: get form data in react 
Javascript :: js copy span text to clipboard 
ADD CONTENT
Topic
Content
Source link
Name
1+4 =