Skip to content

Instantly share code, notes, and snippets.

@nicolasembleton
Created June 30, 2013 16:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicolasembleton/5895896 to your computer and use it in GitHub Desktop.
Save nicolasembleton/5895896 to your computer and use it in GitHub Desktop.
jQuery plugin to detect caret position within a text input. And method to get the current word at caret position.
/**
* jQuery Plugin to get cursor position
*/
(function ($) {
$.fn.getCursorPosition = function () {
var input = this.get(0);
if (!input) return; // No (input) element found
if ('selectionStart' in input) {
// Standard-compliant browsers
return input.selectionStart;
} else if (document.selection) {
// IE
input.focus();
var sel = document.selection.createRange();
var selLen = document.selection.createRange().text.length;
sel.moveStart('character', -input.value.length);
return sel.text.length - selLen;
}
}
})(jQuery);
// Important, inputBar is a jQuery selector of a <input type="text" />
// Checks where the caret is and collect the word surrounding the caret
function getCurrentWordAtCursorPosition(inputBar) {
var cursorPosition = actionBar.getCursorPosition(),
leftWordBoundary = cursorPosition,
rightwordBoundary = cursorPosition,
command = inputBar.val(),
wordpattern = /\w/, // no digits, no dash, unused, here for the taking
recognizerPattern = /(\w|\d|-|#+)/,
currentPattern = recognizerPattern;
// TODO: This case covers the case where the caret is "after" the word
// It won't cover the case where the caret is "before" the word
if(command.charAt(leftWordBoundary).match(/\b|\w/) || command.charAt(leftWordBoundary) == "") {
leftWordBoundary--;
}
while(command.charAt(leftWordBoundary).match(currentPattern)) {
leftWordBoundary--;
}
// if(command.charAt(leftWordBoundary).match(/\b/)){
//
// }
while(command.charAt(rightwordBoundary).match(currentPattern)) {
rightwordBoundary++;
}
return command.slice(leftWordBoundary+1,rightwordBoundary);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment