Fernando Guillén

a Freelance Web Developer

cabecera decorativa

software development as an artistic expression

jQuery: returning the last word from textarea’s cursor

I was enjoying trying to develop a kind of completor suggestor on a textarea, I wanted it to jump when the tab key was pressed, that what easy with capturing the keydown event and the help of event.preventDefault.

But the thing what wasn’t such easy was the capturing the last word on the textarea from the cursor.

But with the help of the code of the insertAtCaret function I was abble to obtain it:

jQuery.fn.lastWord = function() {
  var buffer = '';
 
  this.each(function(){
    if (this.selectionStart || this.selectionStart == '0') {
      var startPos = this.selectionStart;
      var endPos = this.selectionEnd;
      var scrollTop = this.scrollTop;
 
      var index = 0;
      var new_char = '';
 
      do{
        index += 1;
        buffer = new_char + buffer;
        new_char = this.value.substr(startPos - index, 1);
      } while( new_char.search( /^(\w|\.)$/|> ) != -1 )
 
    } else {
      alert("lastWord not supported on this navigator");
    }
  });
 
  return buffer;
};

Example of use:

alert( "last word from cursor: " + $('#my_textarea').lastWord() );

Don’t copy and paste from here, WP does weird stuff with code, download from here: http://gist.github.com/143808

This script is almost not tested, it works for me on FireFox 3.0.11 and Safari 4.0.1, so use it under your own responsability.

2 Comments to “jQuery: returning the last word from textarea’s cursor”
  1. Fernando Guillen, un Desarrollador Web Freelance » Blog Archive » jQuery: deleting the last word from textarea’s cursor Says:

    […] nada por aquí y nada por allá ó el desarrollo de software como expresión artística. « jQuery: returning the last word from textarea’s cursor […]

  2. online stock trading guru Says:

    Hey, great blog…but I don’t understand how to add your site in my rss reader. Can you Help me, please :)

    I’m Out! :)

Leave a comment

a Freelance Web Developer is proudly powered by WordPress
Entries (RSS) and Comments (RSS).