Home > Software engineering >  How to enter into a editable "p" with an id when the enter key is pressed
How to enter into a editable "p" with an id when the enter key is pressed

Time:12-19

<p contenteditable="true" spellcheck="false" id="main"></p>

I want to enter the "main" p when I press the Enter Key. JS Code:

document.addEventListener('keydown', (e) => {
    if(e.code === 'Enter' || e.code === 'NumpadEnter') {
        e.preventDefault();
        if(document.getElementById("main").innerHTML == "sudo apt update") {
            document.getElementById("main").innerHTML = "";
            document.getElementById("main").innerHTML = "checking for updates...";
        }
        newLine();
        
    }
});

I tried to google how to do it but I couldn´t find a way to do it.

CodePudding user response:

  1. You should probably use textContent instead of innerHTML.

  2. In case you want to do something else with the event of a different key move the preventDefault within the inner condition.

  3. Use focus to move the cursor to the editable paragraph element.

// Cache the element
const main = document.querySelector('#main');

// Add a listener to the element
document.addEventListener('keydown', handleKey);

function handleKey(e) {
  if (e.code === 'Enter' || e.code === 'NumpadEnter') {

    // Prevent the event from adding a return in
    // the element, `focus` on the element, and then update
    // its text
    if (main.textContent === 'sudo apt update') {
      e.preventDefault();
      main.focus();
      main.textContent = 'checking for updates...';
    }
  }
}
<p id="main" contenteditable>sudo apt update</p>

CodePudding user response:

To enter into the p element with the main ID when the Enter key is pressed, you can use the focus method:

document.addEventListener('keydown', (e) => {
    if(e.code === 'Enter' || e.code === 'NumpadEnter') {
        e.preventDefault();
        if(document.getElementById("main").innerHTML == "sudo apt update") {
            document.getElementById("main").innerHTML = "";
            document.getElementById("main").innerHTML = "checking for updates...";
        }
        newLine();

        // Focus the main element
        document.getElementById("main").focus();
    }
});

This will give the p element with the main ID focus, which will allow the user to type into it. Note that you may also need to handle the blur event on the element to ensure that it remains focused when the user clicks outside of it.

  • Related