I am working on an online HTML text editor having features to format block like add bold, italics, code block.
So, contenteditable dev by default mimics the style and element on pressing enter
. So, if the current element is pre
and I press enter
it adds a new pre
block. I want it to enter a p
block, so I did it by execCommand
. Here is the code:
document.onkeyup = function( event ) {
if (event.keyCode == 13 ) {
document.execCommand( 'formatBlock', false, 'p' );
event.stopPropagation();
event.preventDefault();
}
}
It works fine, but there is a flicker, it first adds a pre
block and then formats it to p
. How can I debug the reason or fix it?
GIF to explain it properly.
UPDATE: so, found the issue, it is happening as while in contenteditable mode, browsers add new element on keydown and I am trying to format the block in keyup, so the delay. But the new issue is, we can not format the block before it is created in keydown, will try to come up with a solution to add an element by code and prevent default behavior for this and update it as an answer here.