I encountered an issue where a function was not working properly, but strangely, setting a breakpoint in devtools made it work successfully. Why is this happening?
function insertHtmlAtCursor() {
var range=window.getSelection().getRangeAt(0);
var node = range.createContextualFragment("<div>this is not show</div>");
range.insertNode(node);
}
However, when I changed the code to the following, it always ran correctly.
var node = document.createTextNode('this is ok.');
I am using Chrome on MacOS, and here is a demo of the issue:
editor.onkeydown=editinput;
function editinput(e) {
if(e.isComposing||e.keyCode===229) {
return;
}
if(e.keyCode==32) {//space
var range=window.getSelection().getRangeAt(0);
var node=range.createContextualFragment('ttttttttttt');
range.insertNode(node);
}
}
<div id="editor" contenteditable="true" class="knowleadge" tabIndex="1">
</div>
This demo shows that when I press space, it does not insert the fragment, but while debugging in Chrome, it does insert the fragment.
Thanks to @Dekel, I learned that replacing keydown with keyup might be a solution. However, since I need to handle tab as well, keyup cannot accurately capture the tab key. How can I address this in my code?
I discovered that using setTimeout can solve these issues, but I'm wondering if there are any other solutions. Here is the set timeout implementation:
if(e.keyCode==32) {//space
setTimeout(dealpace,0);
e.stopPropagation();
e.preventDefault();
}
function dealpace() {
var range=window.getSelection().getRangeAt(0);
var node=range.createContextualFragment('ttttttttttt');
range.insertNode(node);
}
Thank you @Dekel, the key wasn't really settimeout, but rather e.preventDefault(); As @Dekel mentioned, keydown inserts the text, while keyup replaces the text with space. Therefore, we need to use e.preventDefault(); like so:
if(e.keyCode==32) {//space
dealpace();
e.stopPropagation();
e.preventDefault();
}
function dealpace() {
var range=window.getSelection().getRangeAt(0);
var node=range.createContextualFragment('ttttttttttt');
range.insertNode(node);
}