I know there are many similar topics but none of them has the solution to my problem so please read my question carefully before sending similar topic links and marking as duplicate question.
I have a content editable DIV
object, something similar to TextArea
control. My goal is to cancel key press events if content starts scrolling and there must be no flickering.
When i use keyUp event, it's too late to cancel and there is also no methods available to cancel changes. What's done is done at this stage.
When i use keyDown or keyPress events, they are cancelable. But new changes are not yet applied. So, i know which character is pressed etc. but i still don't know how it's going to affect the scrolling size.
Plus, i allow style changes like making the text bold or changing the font size. Since there is;
document.execCommand("undo");
command, i'm able to test these changes and undo if scrolling starts. To test things, i use a cloned div with same content. It works fine. Changes are applied to cloned div (which is visible at the moment for debugging purposes but will be invisible if the method works) and if cloned div has an overflow, changes are canceled.
My problem is at doing the same thing for key presses. It's harder to simulate what happens to editable div content than using document.execCommand
for other styling options. What i need is to get the innerHTML
result at keyUp
stage before keyUp
occurs and event is still cancelable like keyDown
or keyPress
.
To simulate things, i tried getting cursor position and adding pressed characters manually using substring
function but content isn't plain text and i had many problems with it. For instance when i press enter, an HTML block <div><br></div>
is added for newline character which messed up cursor position. I tried many ways to handle things but it's very open to bugs. So, i decided not to follow this path.
In short my question is;
How can i possibly limit an editable div area by height, not allowing to overflow or scroll without any flickering, just canceling key press events? Do i have to simulate something like willKeyUp or is there any other cross browser way?
Here is jsfiddle link for my sample which works for document.execCommand
case (changing font size, weight etc.) but fails at typing letters;
Edit: To clarify my goal at jsfiddle example, after writing 5 lines of text, either when you press enter or type to end of the line, cursor should never reach to the sixth line. Key presses should be canceled and cursor should stay at fifth line with no content changes or flickers.