Bind "Ctrl + Alt + L" to insert some predefined string into the focused text area?

Is it possible to bind Ctrl+ Alt+ Lto insert a predefined line into the focused textarea at the cursor position? For example, I type in textarea, then press Ctrl+ Alt+ Land <a href="" title=""></a>paste at the current cursor position.

+3
source share
2 answers

Yes. Use the event keydownand one of the functions of the caret-position-in-textarea function that move over the stack overflow. To detect the key, note that I had to use an event keydown, not an event keypress(this is what should be used to determine which character was entered), because IE does not fire events keypressfor Ctrl + Alt + L, so this can go not so on keyboards with different displays. For the cursor position, I copied from this answer and used something similar to myself. Check out these answers to discuss issues with this in IE:

Caret position in the text box, in characters from the beginning Is there an Internet Explorer-approved option for selectStart and selectionEnd?

, , - , .

function getCaret(el) {
    if ("selectionStart" in el) {
        return el.selectionStart;
    } else if (document.selection) {
        el.focus();

        var r = document.selection.createRange();
        if (r == null) {
            return 0;
        }

        var re = el.createTextRange(), rc = re.duplicate();
        re.moveToBookmark(r.getBookmark());
        rc.setEndPoint("EndToStart", re);

        return rc.text.length;
    }
    return 0;
}

var textArea = document.getElementById("yourTextarea");
textArea.onkeydown = function(evt) {
    evt = evt || window.event;
    if (evt.ctrlKey && evt.altKey && evt.keyCode == 76) {
        var cursorPos = getCaret(this);
        this.value = this.value.slice(0, cursorPos)
                   + '<a href="" title=""></a>'
                   + this.value.slice(cursorPos)
        return false; // Prevent any default browser behaviour
    }
};
+1

Ctrl-Alt-L, . :

<textarea name="MyText" id="MyText" onKeyPress="handleKey(this);" 
onKeyDown="CaptureKeyDown(this);"></textarea>

<script>
    function handleKey(ta) {
        if (event.keyCode == 12) { // Ctrl-L
            // Do your insert here
        }
    }
</script>

, . HTML- ( HTML JavaScript) http://www.boltbait.com/htmleditor/ ( ).

EDIT: ! jquery.

0

Source: https://habr.com/ru/post/1744050/


All Articles