Q:

How to get the textbox's id by cursor position

I have multiple textboxes inside a div element. I want to insert some text one of the textbox by cursor position on a button click. I am successfully inserted text if I know the id of a textbox, but i am having problem to know the element wheres the cursor currently positioned.
<div>

    <input type="text" id="txt1" />
    <input type="text" id="Text2" />
    <input type="text" id="Text3" />
    <input type="button" value="Add" id="btnAdd" />
    </div>

$('#btnAdd').click(function () {
            insertDataVarables(document.getElementById('txt1'), 'insertedText')
    });

    function insertDataVarables(myField, myValue) {
        //IE support
        if (document.selection) {
            myField.focus();
            sel = document.selection.createRange();
            sel.text = myValue;
        }
        //MOZILLA and others
        else if (myField.selectionStart || myField.selectionStart == '0') {
            var startPos = myField.selectionStart;
            var endPos = myField.selectionEnd;
            myField.value = myField.value.substring(0, startPos)
                + myValue
                + myField.value.substring(endPos, myField.value.length);
            myField.selectionStart = startPos + myValue.length;
            myField.selectionEnd = startPos + myValue.length;
        } else {
            myField.value += myValue;
        }
    }

So how could I know the textbox id by cursor position.
Thanks in advance

A:

To catch the focused input when clicking a button, you have to listen to the mousedown event as it fires before the input loses focus.
The click event is too late, the input has already lost focused by that time.
To get the currently focused (active) element, one can use document.activeElement.
So something like this :
$('#btnAdd').on('mousedown', function() {
  var el = document.activeElement;

    insertDataVarables(el, 'insertedText')
});

FIDDLE

