Javascript help | Rename paragraph

Asked

Viewed 44 times

0

Ola would like to know the following, as I would logica to rename a paragraph directly by html, for example. I have an empty paragraph, the user clicks on the paragraph and type a word from enter and the word arrow its value in the paragraph. A system of renaming.

  • If I understood your question, you could open a prompt for the person to type, and what she typed you would enter in a <p> tag. Is that it? If yes, you would need to use Javascript to intercept the paragraph click, open the prompt and then assign what was typed to the tag that was clicked.

  • Your logic is strange, as well as clicking on an empty paragraph, if the paragraph is empty as the user will know that there is a paragraph there??

  • <p contentEditable = "true">teste</p> should be the fastest way. This Trona an editable html element.

1 answer

0


Keep in mind that user entries are provided by the element input. Starting from this principle we can follow the steps below:

  1. Create the element input when the user clicks on the paragraph.
  2. Get the value of input when the user presses the key enter.
  3. Insert the figure obtained in the paragraph

document.getElementById("editavel").addEventListener("click", editar);

function editar() {
  const paragraph = this;

  //Criando o input
  const input = document.createElement("input");
  input.id = "input-text";
  input.type = "text";
  input.value = paragraph.innerText;

  //Substituindo o parágrafo pelo input recém criado
  paragraph.parentNode.replaceChild(input, paragraph);
  
  //Focando no elemento criado para melhorar experiência do usuário
  input.focus();
  
  //Identificando a tecla enter para salvar o texto digitado
  input.addEventListener("keypress", function(event) {
    const key = event.which || event.keyCode;
    if (key === 13) {
      saveText();
    }
  });
};

function saveText() {
  const input = document.getElementById("input-text");

  //Criando o novo parágrafo
  const newParagraph = document.createElement("p");
  newParagraph.id = "editavel";
  newParagraph.innerText = input.value;

  //Substituindo o input pelo parágrafo
  input.parentNode.replaceChild(newParagraph, input);

  //Adicionando o evento de click no novo elemento
  newParagraph.addEventListener("click", editar);
};
* {
  margin: 5px;
  padding: 5px;
}

p {
  width: 70%;
  height: 30px;
  background-color: #f4f4f4;
  display: flex;
  align-items: center;
  border: 1px solid black;
}

input {
  width: 70%;
  height: 30px;
  background-color: #f4f4f4;
  border: none;
}
<div>
  <p id="editavel"></p>
</div>

  • Awesome, thank you very much partner.

  • You’re welcome, I’m happy to help you! xD

Browser other questions tagged

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