Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use local storage on append child

<button id="showlinks" onclick="myFunction">show</button>
<div id="buttonlinks"></div>
function myFunction() {
  var button = document.createElement("button");
  document.getElementById("buttonlinks").appendChild(button);
}

I used This Code to create buttons on clicking a button. when clicking the show button the buttons appear but after refresh they are gone.

can I store the buttons with localStorage?


1 Answers

You can store the information about your buttons in the localStorage whenever you create a button, and add an eventListener to window.onload to read the buttons from localStorage and append it to the page when page has loaded, in the below exmpale to keep it simple, I just store the length of buttons.

<button id="showlinks" onclick="myFunction">show</button> <div id="buttonlinks"></div>

js:

 let buttonsLength = 0;

 document.getElementById('showlinks').addEventListener('click', function () {
    createButton();
    buttonsLength++;
    localStorage.setItem('buttonsLength', buttonsLength)
  });

  function createButton() {
    var button = document.createElement('button');
    button.innerHTML = 'click me';
    document.getElementById('buttonlinks').appendChild(button);
  }

  window.addEventListener('load', (event) => {
    buttonsLength = Number(localStorage.getItem('buttonsLength')) || 0;
    for (let i = 0; i < buttonsLength; i++) {
      createButton();
    }
});
like image 114
Saeed Shamloo Avatar answered Jan 26 '26 23:01

Saeed Shamloo