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: it updates the second I click on the div and not after some text is entered.
What I want is: to save changes after entering the text. Is there any substitute of onclick or any other method that I can achieve this?
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.
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>