shane shane - 24 days ago 6x
Javascript Question

Detecting that a textarea is focused during a button click


I have a textarea and a button. When I click the button, I want to insert text into the textarea. However, the text that I insert depends upon the current focus of the texteara. Here are some cases:


(As of the time that the button is clicked)

  • Textarea focused

    • Insert text where the cursor is, as-is

  • Textarea unfocused

    • Insert text at the end of the textarea (ie add a newline to the inserted text)

Example / Attempt

Here is a fiddle with my example implementation:

$(document).ready(function() {
$('button').click(function() {
var $text = $('textarea');

var currentValue = $text.val(),
len = currentValue.length,
isTextAreaFocused = $':focus'),
optionalNewline = isTextAreaFocused ? '' : '\n';

var start = $text[0].selectionStart,
end = $text[0].selectionEnd,
beforeText = isTextAreaFocused ? currentValue.substring(0, start) : len,
afterText = isTextAreaFocused ? currentValue.substring(end) : len;

var insertedText = 'foo',
newValue = beforeText + insertedText + afterText + optionalNewline;



I believe that the button focuses before it has a chance to know if the textarea is focused. Is there a hook or way to handle the click event on the button such that I'll know (before it is focused) what is focused?

Off point: I'm using Ember as my framework. I'd really love to see a pure JS / jQuery solution, but I just wanted to place Ember on the table as well.


You'd have to use the mousedown event on the button, as it fires before the textarea loses focus.
By the time a click event fires, the mouse has been pressed down, and released, and the focus will have shifted to the button instead.

$(document).ready(function() {
          mousedown: function() {
            var text              = $('textarea').get(0),
                currentValue      = text.value,
                isTextAreaFocused = text === document.activeElement,
            	insertedText      = 'foo',
                start             = text.selectionStart,
                end               = text.selectionEnd,
                beforeText        = currentValue.substring(0, start) || "",
                afterText         = currentValue.substring(end) || "",                   
                newValue          = beforeText + insertedText  + afterText;
             text.value = isTextAreaFocused ? newValue : currentValue + insertedText + '\n';
             $(this).data({'focus' : isTextAreaFocused, 'end' : end + insertedText.length});
          mouseup: function() {
              if ( $(this).data('focus') ) {
                  $('textarea').focus().get(0).setSelectionRange($(this).data('end'), $(this).data('end'));
textarea {
  width: 20em;
  height: 10em;
<script src=""></script>
<button>Insert text</button>