I have a div which is being used as a user-friendly text editor on my school-project website. However if I select all of the text inside the editor and attemp to surround it with <code> tags </code>
I can not get the cursor out of it, it keeps adding whatever i type into the same tag, which is <code>
.
After some time I gave up on it, but then I found this answer and tried to modify the jsfiddle that is mentioned there in the hopes of getting it to work. But no luck.
If I, lets say, select the last word in any line and surround it with <code>
tags, I am able to get the cursor out of it where there is non-surrounded text but on the end there's no plaintext to jump onto so the cursor is stuck in <code>
How can I make sure that the cursor doesn't get stuck in added tags?
maybe a way to move the cursor out of it?
jsFiddle
function surroundSelection() {
var code = document.createElement("code");
code.style.fontStyle = "italic";
code.style.color = "#333";
code.style.background = "#ddd";
if (window.getSelection) {
var sel = window.getSelection();
if (sel.rangeCount) {
var range = sel.getRangeAt(0).cloneRange();
range.surroundContents(code);
sel.removeAllRanges();
sel.addRange(range);
}
}
}
div, input {
padding:10px;
}
div {border:1px solid;}
<input type="button" onclick="surroundSelection()" value="Surround">
<div contenteditable="true">One two three four</div>
hello
': '', 'nbsp;': ''` any clue why this happens ? – Feelsbadman Jan 02 '19 at 21:43