views:

53

answers:

2

Hello,

Is is possible to bind Ctrl+Alt+L to insert predefined string into focused textarea to cursor position? For example, I'm typing some text in textarea, then I'm pressing Ctrl+Alt+L and <a href="" title=""></a> is inserted into current cursor position.

Thank you.

A: 

I'm not sure about Ctrl-Alt-L, but there are definately ways to do this. For example:

<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>

It is more complicated than this. Check out this HTML editor (written in HTML and JavaScript) at http://www.boltbait.com/htmleditor/ (the source can be downloaded there).

EDIT: Oops! I didn't see your jquery tag.

BoltBait
It's not a problem, it's ok without jQuery.
Kirzilla
A: 

Yes. Use the keydown event and one of the caret-position-in-textarea functions floating around on Stack Overflow. For the key detection, note I've had to use the keydown event rather than the keypress event (which is what should be used for detecting what character has been typed) because IE doesn't fire the keypress events for Ctrl+Alt+L, so this could go wrong on differently mapped keyboards. For the cursor position, I've copied from this answer and have used something similar myself. See these answers for discussion of the problems with this in IE:

http://stackoverflow.com/questions/263743/how-to-get-cursor-position-in-textarea http://stackoverflow.com/questions/235411/is-there-an-internet-explorer-approved-substitute-for-selectionstart-and-selectio/235582#235582

Also, note that you may want to position the cursor somewhere sensible after doing this, which my code doesn't cover.

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
    }
};
Tim Down