Skip to content

Instantly share code, notes, and snippets.

@cope
Created December 29, 2020 17:02
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 cope/db299e657b4ce0d8dab66947b611f97a to your computer and use it in GitHub Desktop.
Save cope/db299e657b4ce0d8dab66947b611f97a to your computer and use it in GitHub Desktop.
let foobar = document.getElementById('foobar');
foobar.addEventListener('keyup', e => {
let value = e.target.value;
let typing = _.endsWith(value, ' ');
let cursor = e.target.selectionStart;
let addSpace = _.endsWith(value, ' ');
let words = _.split(value, ' ');
words = _.map(words, _.trim);
let size1 = _.size(words);
words = _.compact(words);
let size2 = _.size(words);
if (!typing && size1 !== size2) e.target.value = _.join(words, ' ');
let word = _.first(words);
if (cursor > _.size(word)) {
if (cursor > 0) cursor--;
let cut = _.truncate(value, {
length: cursor,
separator: ' ',
omission: ''
});
let remain = _.trim(_.replace(value, cut, ''));
word = _.first(_.split(remain, ' '));
if (!word) word = _.last(words);
}
console.log('Caret at: ', e.target.selectionStart, word)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment