Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

141
Visualizações
Saving values to localStorage() and making them stay when I reload the page in Javascript

I am currently making a note writing app and need your help.

I'm struggling to understand how localStorage() works and how exactly I saved things to it. I would like to reload the page and have every note that I've written not dissappear.

Thank you.

//// Declare Variables ////
const noteBtn = document.querySelector('.add-note-btn');
const writeNote = document.querySelector('.note-input');
const allSavedNotes = document.querySelector('.added-notes');

//// Write new note and add to list ////
noteBtn.addEventListener('click', function(e){
  // Create new paragraph element
  let newNote = document.createElement('p');
  // Add clas name to element
  newNote.className = 'saved-note';
  // Add the text input
  newNote.textContent = writeNote.value;
  // Append element to div
  allSavedNotes.appendChild(newNote);

  e.preventDefault();
})
<div class="all">
    <div>
      <div class="title">
        <h1 class="heading">Notes List</h1>
      </div>

      <div>
        <div class="writing-notes">
          <textarea class="note-input" cols="35" rows="10"></textarea>
          <a href="#" class="add-note-btn">Add note</a>
        </div>
        
        <div class="added-notes">
    
        </div>
      </div>
    </div>
  </div>

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can save all notes in localStorage by appending the state to an empty array.

I've intitally created a state variable that contains earlier undefined or an empty array.

Then appendNotes function appends a paragraph to the allSavedNotes DOM selector.

//// Declare Variables ////
const noteBtn = document.querySelector('.add-note-btn');
const writeNote = document.querySelector('.note-input');
const allSavedNotes = document.querySelector('.added-notes');

const state = JSON.parse(localStorage.getItem('notes')) || [];

function appendNotes(text) {
  let p = document.createElement('p');
  p.textContent = text;
   
  // Append element to div
  allSavedNotes.appendChild(p);
}

// append notes on page load
state.map(s => appendNotes(s));

//// Write new note and add to list ////
noteBtn.addEventListener('click', function(e) {
  // Create new paragraph element
  let newNote = document.createElement('p');
  // Add class name to element
  newNote.className = 'saved-note';
  
  const text = writeNote.value.trim();

  // Add the text input
  newNote.textContent = text;
  
  // if there are no `notes` in `localStorage` then use empty array
  if (text !== "") {
      state.push(text)
    localStorage.setItem('notes', JSON.stringify(state));
   }
   
  // Append element to div
  appendNotes(text);
  
  newNote.textContent = "";
  
  e.preventDefault();
})
<div class="all">
  <div>
    <div class="title">
      <h1 class="heading">Notes List</h1>
    </div>

    <div>
      <div class="writing-notes">
        <textarea class="note-input" cols="35" rows="10"></textarea>
        <a href="#" class="add-note-btn">Add note</a>
      </div>

      <div class="added-notes">

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

The above code won't from StackOverflow directly as it gives a cross-origin error:

Uncaught SecurityError: Failed to read the 'localStorage' property from 'Window': The document is sandboxed and lacks the 'allow-same-origin' flag.

But it works on JSFiddle. Here's a working link → https://jsfiddle.net/deadcoder0904/036bp9zy/33/

You can learn more about localStorage in this excellent blog post → https://www.digitalocean.com/community/tutorials/js-introduction-localstorage-sessionstorage

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda