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

143
Visualizações
Script is hard to manage

I'm planning to increase the number of elements in the "source" div from two to three. But in order to increase it, I need to create a lot of new lines of code with pretty much the same data (const three, new fuction appendIt2 and add an extra if in the window.onload).

Maybe you can advise how can I reduce the clutter in this script and make it easier to edit and read?

const one = document.getElementById("element");
element.addEventListener("click", appendIt);

function appendIt() {
  localStorage.setItem("append", "true");
  var element = document.getElementById("element");
  document.getElementById("destination").appendChild(element);
}

const two = document.getElementById("element1");
element1.addEventListener("click", appendIt1);

function appendIt1() {
  localStorage.setItem("append1", "true");
  var element1 = document.getElementById("element1");
  document.getElementById("destination").appendChild(element1);
}


window.onload = () => {
  if (localStorage.getItem("append") == "true") {
    appendIt();
  }
  if (localStorage.getItem("append1") == "true") {
    appendIt1();
  }
};

function clearstorage() {
  localStorage.clear();
  location.reload();
}
#destination {
  display: flex;
  flex-direction: column;
  background-color: red;
}

#source {
  display: flex;
  flex-direction: column;
  background-color: beige;
}
<button onclick="clearstorage()">
  Reset order
</button>
<div id="destination"></div>
<div id="source">
  <a id="element" href="#">One</a>
  <a id="element1" href="#">Two</a></div>

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

0

First, create a generic function to append

function append(itemName, elementId) {
  localStorage.setItem(itemName, "true");
  let element = document.getElementById(elementId);
  document.getElementById("destination").appendChild(element1);
}

In order to use it, pass an arrow function as callback to the event listener, in this way:

theElement.addEventListener("click", () => append("append", "element"));

This would lead to:

function append(itemName, elementId) {
  localStorage.setItem(itemName, "true");
  let element = document.getElementById(elementId);
  document.getElementById("destination").appendChild(element1);
}

const one = document.getElementById("element");
// Use arrow function as callback to pass the proper values to the generic append() function
// I replaced 'element' variable with 'one' here, which is the element you just retrieved
one.addEventListener("click", () => append("append", "element"));

const two = document.getElementById("element1");
two.addEventListener("click", () => append("append1", "element1"));

// When appending new child:
//    const three = document.getElementById("element2");
//    three.addEventListener("click", () => append("append2", "element2"));


window.onload = () => {
  if (localStorage.getItem("append") == "true") {
    append("append", "element");
  }
  if (localStorage.getItem("append1") == "true") {
    append("append1", "element1")
  }
};

function clearstorage() {
  localStorage.clear();
  location.reload();
}
#destination {
  display: flex;
  flex-direction: column;
  background-color: red;
}

#source {
  display: flex;
  flex-direction: column;
  background-color: beige;
}
<button onclick="clearstorage()">
  Reset order
</button>
<div id="destination"></div>
<div id="source">
  <a id="element" href="#">One</a>
  <a id="element1" href="#">Two</a></div>

If you want to go further, you could have a map like:

const appendToElementMap = {
  "element": "append",
  "element1": "append1"
};

and iterate upon its entries to add the event listeners

about 4 years ago · Juan Pablo Isaza Relatório

0

I would suggest to keep your functions in a seperate javascript file in some util folder. That folder should contain files which are serving some meaningful purpose. And, improve your naming convention also, maybe that will ease out the process a bit. It will help you in the long run.

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