Skip to content

Instantly share code, notes, and snippets.

@vickylance
Created July 4, 2024 16:33
Show Gist options
  • Save vickylance/5db550a6664720a3d345df9e4001aa71 to your computer and use it in GitHub Desktop.
Save vickylance/5db550a6664720a3d345df9e4001aa71 to your computer and use it in GitHub Desktop.
var lastActiveElement = document.activeElement;
function setCaretPosition(elem, caretPos) {
if (elem != null) {
if (elem.createTextRange) {
var range = elem.createTextRange();
range.move("character", caretPos);
range.select();
} else {
if (elem.selectionStart) {
elem.focus();
elem.setSelectionRange(caretPos, caretPos);
} else elem.focus();
}
}
}
function keyDownHandler(event) {
if (event.key == "q") {
lastActiveElement.value += "<";
setCaretPosition(lastActiveElement, lastActiveElement.selectionStart + 1);
} else if (event.keyCode == 39) {
lastActiveElement.value += ">";
setCaretPosition(lastActiveElement, lastActiveElement.selectionStart + 1);
}
}
function detectBlur() {
lastActiveElement.removeEventListener("keydown", keyDownHandler);
}
function detectFocus() {
let activeElement = document.activeElement;
if (activeElement.tagName == "INPUT" || activeElement.tagName == "TEXTAREA") {
lastActiveElement = activeElement;
lastActiveElement.addEventListener("keydown", keyDownHandler);
}
}
function attachEvents() {
window.addEventListener
? window.addEventListener("focus", detectFocus, true)
: window.attachEvent("onfocusout", detectFocus);
window.addEventListener
? window.addEventListener("blur", detectBlur, true)
: window.attachEvent("onblur", detectBlur);
}
attachEvents();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment