Is it 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.
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:
Caret position in textarea, in characters from the start Is there an Internet Explorer approved substitute for selectionStart and selectionEnd?
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
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With