Reputation: 1165
I've got a small contenteditable
span on a page. Under some circumstances (pressing the escape key, for example), I'd like to programmatically cancel editing mode.
Is there a way to do that?
So far, I've found only the hack of removing the contenteditable attr and restoring it shortly thereafter (e.g. 100ms later or so) which is cannot possibly be the right way :-( I would imagine I could change the focus for the same effect.
What I really want is elem.endEdit()
or some such...
Thanks!
Upvotes: 2
Views: 1789
Reputation: 29
You can call blur() on the element that is being edited. Here is an example: https://codepen.io/MarcMouries/pen/PowEYRv
<h3>Editable content</h3>
<div contenteditable="true" id="editor">Click me, type something, then press the ESC key</div>
<h3>Events</h3>
<textarea id="log" rows="10" cols="100" readonly></textarea>
var element = document.getElementById("editor");
var eventsLog = document.getElementById("log");
var oldValue = "";
document.addEventListener('keyup', (e) => {
if (event.keyCode == 27) {
eventsLog.value += "ESC key pressed => UNDO reset to (" + oldValue + ")\n";
var element = event.target;
element.textContent = oldValue;
element.blur();
}
}, false);
element.addEventListener("focus", function(event) {
var element = event.target;
oldValue = element.textContent;
eventsLog.value += "FOCUS: value = " + oldValue + "\n";
});
element.addEventListener("blur", function(event) {
var element = event.target;
var newValue = element.textContent;
if(newValue != oldValue) {
eventsLog.value += "Input changed value to: " + newValue + " \n";
}
}, false);
Upvotes: 1