Home > Mobile >  How to change html element after text has been edited
How to change html element after text has been edited

Time:07-12

I have this code that should change the contents of a table position when you change the contents of nameDiv which is var nameDiv = document.createElement('div'); (nameDiv.contentEditable = "true";) and it has some text

 nameDiv.onclick = event => {
            allSectionsArray[sectionNumber][2] = event.value;
 }

What happens here is basically is: when I click on this div, before I write whatever, it updates right when I clicked and basically nothing changes.

What I want is: when I finish entering the text, then to save changes. Is there any substitute of onclick or any other method that I can achieve this?

CodePudding user response:

For contenteditable, you can use the input event:

The input event fires when the value of an input element has been changed.

The change event isn't supported for contenteditable, but you can use the blur event instead which

fires when an element has lost focus

const example = document.querySelector("#example");

example.addEventListener("blur", ()=>{
  console.log(`Value is: ${example.textContent}`);
});
#example {
  border: solid 1px #000;
  padding: 5px;
}
<div id="example" contenteditable></div>


You can also browse the full list of events here.

CodePudding user response:

Find below a sample how different events work with contenteditable elements. You will probably need blur event handler to get the value when user is done typing.

const code = document.querySelector('pre');
const object = {
  valueOnclick: '',
  valueOninput: '',
  valueOnblur: ''
};

document.querySelector('div').addEventListener('input', e => {
  object.valueOninput = e.target.textContent;
  code.innerHTML = JSON.stringify(object, null, 4);
});

document.querySelector('div').addEventListener('click', e => {
  object.valueOnclick = e.target.textContent;
  code.innerHTML = JSON.stringify(object, null, 4);
});

document.querySelector('div').addEventListener('blur', e => {
  object.valueOnblur = e.target.textContent;
  code.innerHTML = JSON.stringify(object, null, 4);
});
<div contenteditable>Some content</div>
<pre></pre>

  • Related