0

I have a contenteditable div with id="textarea" I also have a few buttons that insert different texts/symbols at a cursor position. The problem occurs when I click outside of the textarea div (the text inside of buttons, too); the text/symbol is being inserted outside of the div. How can I prevent this? Can I "force focus" onto that div? I have only one textarea although I may have more in future.

For insertion, I used the code suggested by Tim Down on another thread:

Insert html at caret in a contenteditable div

here is the code for my textarea and buttons.

<div id="textarea" contenteditable="true">
    <style scoped>
        #example-one { margin-bottom: 10px; }
        [contenteditable="true"] { padding: 10px; outline: 2px dashed #CCC; }
        [contenteditable="true"]:hover { outline: 3px dashed #0090D2; }
    </style>
    <p id="inside">
    </p>
</div>

<div id="buttons">
    <button type="button" onclick="pasteProjectionAtCaret()">Π</button>
</div>
Community
  • 1
  • 1
Krzysiek
  • 1,487
  • 4
  • 19
  • 28

1 Answers1

1
document.getElementById('textarea').onblur=function(){
    document.getElementById('textarea').focus();
};

This makes it so that whenever textarea loses focus, Javascript set the focus back immediately, thus not allowing the user to leave.

Robbie Wxyz
  • 7,671
  • 2
  • 32
  • 47