Glr, how do I leave the element that was created fixed on the page even if the page is loaded? When loading the page it disappears

Asked

Viewed 104 times

-2

var listagem = document.getElementById("listagem");

function createNewElement() {
  // Cria a div
  var div = document.createElement("div");
  div.setAttribute("id", "d");

  // Cria a li
  var li = document.createElement("li");
  li.setAttribute("id", "li");

  // Cria o botão
  var check = document.createElement("input");
  check.setAttribute("id", "check");
  check.type = "checkbox";

  // Pega o valor do input digitado
  var texto = document.getElementById("texto").value;
  li.innerText = texto;

  // Adiciona a lista 
  div.appendChild(check);
  div.appendChild(li);
  listagem.appendChild(div);
}
  • If I am not mistaken the information that these elements have already been created should be stored in some way, as in a LocalStorage to generate the elements when the page is loaded, if previously generated.

  • Obg, but is there any way you can show me an example? (Because I’m a "beginner")

  • Puts HTML in question.

  • I just put html and js down there.

2 answers

2


Your question is not clear enough that we can help you. But from my perspective what you are trying to do is try to catch the value of a input="text" and put it inside any element and even if the page is loaded or if you close the page the text will still remain in the specified element. For this, you would have to use a resource that saves the value country input="text" within the specified element, but on your computer. For this, you can use the API local storage in case localstorage there is also the sessionStorage, but in your case use the localstorage for the data not to be lost. I created a simple example from scratch for you, because your example would not match mine too much and would be confusing for you to understand, I will not talk about what I did in the code, because in the code itself is commented. It may be that here on stackoverflow error return. I don’t know, it may be that I’m wrong, but it must be for security reasons because I’m using a API local storage. But the code itself is working normally.

<html>
<head>
  <meta charset="UTF-8">
</head>
<body>

  <!-- Você vai digitar o nome nessa caixa -->
  <input id="new-name" type="text" placeholder="Nome:">
  <!-- Esse botão é o que vai salvar os dados que você digito caixa de texto -->
  <button id="button-new-name" type="button">Novo Nome</button>
  <!-- Esse é o que vai remover -->
  <button id="button-delete-name">Apagar Nome</button>
  <!-- Aqui é aonde vai aparecer o texto que você digitou na caixa de texto -->
  <p id="paragraph"></p>
  <script>
  
    // Variáveis com valores fazendo referência aos atributos id no html.
    let newName = window.document.querySelector("#new-name");
    let buttonNewName = window.document.querySelector("#button-new-name");
    let buttonDeleteName = window.document.querySelector("#button-delete-name");
    let paragraph = window.document.querySelector("#paragraph");

    // O contéudo do parágrafo vai receber o valor da chave Nome.
    // Isso é para quando você carregar a página o nome continuar lá.
    paragraph.textContent = window.localStorage.getItem("Nome");

    // Adicionar um evento de click no button com id button-new-name e chame uma função anônima.
    buttonNewName.addEventListener("click", function()
    {
        // Quando o botão for clicado criar uma chave Nome com o valor do valor de input com id="new-name".
        window.localStorage.setItem("Nome", newName.value);
        // Quando o botão for clicado pegar o valor da chave nome e colocar no parágrafo.
        paragraph.textContent = window.localStorage.getItem("Nome");
        newName.value = "";
    });

    // Adicionar um evento de click no button com id button-delete-name e chame uma função anônima.  
    buttonDeleteName.addEventListener("click", function()
    {
        // Remover a chave Nome que está armazenada no seu PC.
        window.localStorage.removeItem("Nome");
        // O contéudo do paragrafo vai receber nada. Isso é, uma string vazia.
        paragraph.textContent = "";
    });
  </script>
</body>
</html>

  • With this example I’ll probably be able to solve my "problem", but does this Torage save the created tags? Type, document.createElement("p");?

  • Sorry anything, I’m pretty layy still in the programming part.

  • Dude, when you put any tag inside a document and then load the page it’s already rendered not the need to save it. But in case you have some text typed in an input that not even the example I gave in the reply, you would have to store them on the computer that because when you reload the page everything will return in the pattern and the data contained in the input will not remain there.

  • That’s how I thought of doing this checklist, this method was the simplest I could do. I want to check a list of activities, if you have another way that can help me I appreciate, Abçs.

0

Here the complete code.
The html:

<!DOCTYPE html>
<html lang="pt-br">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="css/main.css">
  <link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
  <link rel="icon" href="img/list.png">
  <title>Check List</title>
</head>
<body>
   <div class="main">
    <form action="#">
        <div class="new">
            <input type="text" id="texto">
            <button id="btn">add</button>
            <img src="img/reload.png" onclick="location.reload();">
        </div>
        <div class="lista">
            <ol class="listagem" id="listagem">
            </ol>
        </div>
    </form>
</div>
<script src="js/js.js"></script>
</body>

</html>

The js:

var listagem = document.getElementById("listagem");

function createNewElement() {
  // Cria i Para receber o icon
  var icon = document.createElement("i");
  icon.setAttribute("id", "icon");
  // Cria a div 
  var div = document.createElement("div");
  div.setAttribute("id", "d");
  // Cria a li
  var li = document.createElement("li");
  li.setAttribute("id", "li");
  // Cria o botão 
  var check = document.createElement("input");
  check.setAttribute("id", "check");
  check.type = "checkbox";
  // Pega o valor do input digitado
  var texto = document.getElementById("texto").value;
  li.innerText = texto;
  // Adiciona a lista 
  div.appendChild(check);
  li.appendChild(icon);
  div.appendChild(li);
  listagem.appendChild(div);
}


function verificarCheck() {
  var li = document.querySelectorAll("li");
  var check = document.querySelectorAll("input#check");

  for (let i = 0; i < check.length; i++) {
      for (let i = 0; i < li.length; i++) {
          if (check[i].checked) {
              check[i].style.display = "block";
              li[i].style.textDecoration = "line-through";
              //icon[i].setAttribute("class", "material-icons");
              //icon[i].innerText = "add";
          } else {
              // Nada
          }
        }
    }
}
setInterval(verificarCheck, 100);

const btn = document.getElementById("btn");
btn.addEventListener("click", function() {
    var li = document.querySelectorAll("li");
    var texto = document.getElementById("texto").value;
    if (texto) {
        createNewElement();
        document.getElementById("texto").value = "";
    } else {
        // Nada
    }
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.