Home > Mobile >  Moving and keeping an element
Moving and keeping an element

Time:05-05

Once I press " " sign and the element is moved to the "destination" div, what would be the easiest way with the help of local storage to keep an "element" in the "destination" div after the page is refreshed?

function appendIt() {
  var element = document.getElementById("element");
  document.getElementById("destination").appendChild(element);
}
#destination {
  background-color:red;
}

#source {
  background-color:beige;
}
<div id="destination"></div>
<div id="source">
  <a id="element"href="#" onclick="appendIt()">One</a></div>

CodePudding user response:

As you mentioned with localStorage, you can add some flag in local storage inside appendIt() function. And on windows load event you can check if that flat is there in local storage and what value it have. Based on that value you can again call appendIt() as per requirement.

function appendIt() {
  // set value to local storage with key append
  localStorage.setItem("append", "true");
  var element = document.getElementById("element");
  document.getElementById("destination").appendChild(element);
}

// Add windows load event to check local storage
window.onload = (event) => {
  // check local storage for key append and if its value is true then call appendIt function
  if (localStorage.getItem("append") == "true") {
    appendIt();
  }
};
#destination {
  background-color: red;
}

#source {
  background-color: beige;
}
<div id="destination"></div>
<div id="source">
  <a id="element" href="#" onclick="appendIt()">One</a></div>

CodePudding user response:

One way is to keep the innerHtml of that div in LocalStorage and on page refresh check if anything exists there and if exists append in the div.

CodePudding user response:

You want to create a deep clone before appending the element. This is achieved by calling cloneNode(true) on the element:

document.getElementById("destination").appendChild(element.cloneNode(true));
  • Related