Reputation: 1589
var editBtn = document.querySelector("button#edit"),
editable = editBtn.previousElementSibling,
saveBtn = editBtn.nextElementSibling;
editBtn.addEventListener('click', startEdit, false);
saveBtn.addEventListener('click', endEdit, false);
function startEdit() {
editable.setAttribute("contenteditable", true);
editable.focus();
}
function endEdit() {
editable.setAttribute("contenteditable", false);
// even tried
// editable.removeAttribute("contenteditable");
}
body {
background-color: #ccc;
}
p[contenteditable="true"] {
font-family: "Arial", "Georgia", "Calibri";
background-color: #fff;
font-size: 14px;
padding: 4px;
color: #424245;
border: 1px solid #C7C6CD;
}
<p>click edit, type some mispelled words, click save and highlighting remains</p>
<button id="edit">edit</button>
<button>save</button>
I have a feature application that sets contenteditable="true"
on a <p></p>
element
when an edit button is clicked, then set it to false
when the ENTER key is pressed.
Now after the ENTER key is pressed and contenteditable="false"
is set on the element, all misspelled words highlighted remain highlighted even though now the element is no longer editable.
Is there a way to remove the highlighting of misspelled words in this case.
I had problem running the code snippet in the editor, so if there's any problem please let me know.
Upvotes: 4
Views: 136
Reputation: 3950
The easiest way is probably to just overwrite the content with itself:
var html = editable.innerHTML;
editable.innerHTML = "";
editable.innerHTML = html;
Emptying the content first is necessary, unfortunately.
Simply editable.innerHTML = editable.innerHTML;
doesn't seem to work.
var editBtn = document.querySelector("button#edit"),
editable = editBtn.previousElementSibling,
saveBtn = editBtn.nextElementSibling;
editBtn.addEventListener('click', startEdit, false);
saveBtn.addEventListener('click', endEdit, false);
function startEdit() {
editable.setAttribute("contenteditable", true);
editable.focus();
}
function endEdit() {
editable.setAttribute("contenteditable", false);
var html = editable.innerHTML;
editable.innerHTML = "";
editable.innerHTML = html;
}
body {
background-color: #ccc;
}
p[contenteditable="true"] {
font-family: "Arial", "Georgia", "Calibri";
background-color: #fff;
font-size: 14px;
padding: 4px;
color: #424245;
border: 1px solid #C7C6CD;
}
<p>click edit, type some mispelled words, click save and highlighting remains</p>
<button id="edit">edit</button>
<button>save</button>
Upvotes: 1