jeudi 29 septembre 2016

Detecting that a textarea is focused during a button click

Explanation

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:

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: http://ift.tt/2cEe9lu

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

        var currentValue = $text.val(),
            len = currentValue.length,
            isTextAreaFocused = $text.is(':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; 

        $text.val(newValue);
    });
})

Problem

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.




Aucun commentaire:

Enregistrer un commentaire