home ~ projects ~ socials

JavaScript Local Storage Example

This is the basic way I'm storing text strings in local storage in a browser.

Store Basic Text

JavaScript

function updateLocalStorage(value) {
  localStorage.setItem(
    "post-2n8nzsup-example", value
  )
}

Get Basic Text

JavaScript

function getFromLocalStorage() {
  const storedValue = 
    localStorage.getItem("post-2n8nzsup-example")
  const el = 
    document.querySelector("#current-in-storage")
  el.innerHTML = storedValue
}

Example

Output

Currently In Storage:

HTML

<div>
  <label for="example-text">Send To Storage</label>
  <input id="example-text" name="example-text" type="text" value="Text To Store" />
</div>

<div>
  Currently In Storage: 
  <span id="current-in-storage"></span>
</div>

Supporting Script

JavaScript

document.addEventListener("DOMContentLoaded", () => {
  getFromLocalStorage()
  const el = document.querySelector("#example-text")
  el.addEventListener("input", (event) => {
    const value = event.target.value
    updateLocalStorage(value)
    getFromLocalStorage()
  })
})
-- end of line --