skip to Main Content

I was trying to make something for my wiki with js that when you click on a text it turns it into textarea with a button and when you click the button it updates the text.

I tried adding button with changing a div value but it didn’t work.

2

Answers


  1. You could hide the paragraph element when it’s clicked, and add a textarea and button after it. Then assign an event listener to the button to update the paragraph’s textContent and display it again.

    A basic example:

    document.querySelector('p').addEventListener('click', function(e) {
      // Consider putting these two elements in a container
      const textarea = document.createElement('textarea'),
        btn = document.createElement('button');
      textarea.value = this.textContent;
      btn.textContent = 'Save';
      btn.addEventListener('click', () => {
        this.textContent = textarea.value;
        this.style.display = '';
        textarea.remove();
        btn.remove();
      });
      this.style.display = 'none';
      this.after(textarea, btn);
    });
    <p>Some text</p>
    Login or Signup to reply.
  2. You can simply use contenteditable property

    const 
      p_EditOnOff = document.querySelector('p')
    , btn_EditOff = document.querySelector('#btn-EditOff')
      ;
    
    p_EditOnOff.addEventListener('click', () =>
      {
      if ( p_EditOnOff.contentEditable === 'true') return;
      p_EditOnOff.contentEditable = true;
      btn_EditOff.classList.toggle('noDisplay',false);
      
      p_EditOnOff.focus();
      })
    
    btn_EditOff.onclick =_=>
      {
      btn_EditOff.classList.toggle('noDisplay',true);
      p_EditOnOff.contentEditable = false;
      }
    .noDisplay {
      display: none;
    }
    
    p[contenteditable="false"] {
      cursor: pointer;
    }
    <p contenteditable="false">Some text</p>
    
    <button id="btn-EditOff" class="noDisplay"> end edit </button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search