Created
June 30, 2013 16:43
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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