Note: Please, before marking it as duplicate, understand that I am adding the data dynamically using keypress function in Javascript.
I am trying to create a script that adds data dynamically to a contenteditable div, I am able to do that with the following code.
var enterPressed = 0;
window.onkeypress = function (e) {
var keyCode = (e.keyCode || e.which);
if (keyCode === 13) {
if (enterPressed === 0) {
e.preventDefault();
var z = document.createElement('p'); // is a node
z.innerHTML = "<br><p>R: ";
document.getElementById("textbox").appendChild(z);
enterPressed++;
} else if (enterPressed === 1) {
e.preventDefault();
var z = document.createElement('p'); // is a node
z.innerHTML = "<br><b>M: ";
document.getElementById("textbox").appendChild(z);
enterPressed++;
enterPressed = 0;
}
}
};
So when enter is press once I get M: and if enter is press twice, I get R: and then the function reset.
The problem is that whenever I press enter the caret position still remains at the beginning of the document while ideally, it should be at the end so I can type something further.