Home > Blockchain >  How to make cursor always stay on textarea even if user clicks anywhere else on the page?
How to make cursor always stay on textarea even if user clicks anywhere else on the page?

Time:03-07

I'm developing a Chat application using Angular & Electron.

I want user's cursor always on textarea where user types the message. When user clicks anywhere else in the page, the cursor should not go away from text area. This helps user to type anytime from anywhere, it will type in textarea only.

I tried the following:

    setTimeout(() => {
      this.messageTextAreaInput.nativeElement.focus();
    }, 20);

I'm calling it on the textarea blur event. But this solution does not let me copy text from other messages. When I select any text from message history, my selection is lost.

Any other way to achieve this?

My app for reference: enter image description here

CodePudding user response:

window.addEventListener("keydown", () => {document.getElementById("textarea").focus()});
<textarea id="textarea" ></textarea>

CodePudding user response:

Try this way. You can change focus element to your own element which can be focusable.

const focusOnTextInput = () => document.getElementById('input').focus();

document.addEventListener('click', focusOnTextInput);
document.addEventListener('DOMContentLoaded', focusOnTextInput);
<input type="text" id="input"/>

CodePudding user response:

You could try using something like

window.onclick = function(event) {
    if (!event.target.matches('.messageTextAreaInputClassName')) {
        document.getElementById('messageTextAreaInput').focus();
    }
}

So that clicking anywhere other than the text area will call the text area to focus.

  • Related