Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firing event when caret moves between lines in textarea

Is there a way to have a textarea fire an event if the user changes which line the caret is on, say, by clicking or using the up/down arrows? Or is this just not possible in Javascript? I've found ways to find/set the current position of the caret, but that's not what I need...

like image 546
NumerousHats Avatar asked Nov 17 '11 16:11

NumerousHats


1 Answers

Sounds like you need to register a couple events for your text area. off the top of my head, a click event, and a keypress event with multiple keycode values. Do you need to use pure javascript, or do you have some javascript libraries to utilize?

Do you need help registering events? or do you need help finding the caret position during one of the events? (see andy's link for that) or is the answer to both my questions "yes"?


edit

ok, from you're comments you're ok with jquery, and the fieldselection plugin prevents you from re-inventing the wheel.

  1. identify any keyboard keys, mouse clicks, ?copy paste? events that could move the caret in a text field. Navigate and select portions of text, wikipedia
  2. during the event, use the fieldselection plugin to get the new caret position.
  3. use the current caret position && font size && text box physical size && linebreak count to determine if you've switched to a new line.
  4. if you did switch lines, trigger a custom jQuery event to do the work you want.

//jQuery 1.7

$(document).ready(function(){
  var currentLine = -1;
  $("#textAreaID").on("keypress", function(evt){
   if(evt.which === 40 || ...){
//down arrow key, enter key, page down key, all will move the caret to a newline
     $(this).trigger("newline");
   }else{
//a ton of text in a fixed width textarea will move the cursor to a newline
     $(this).trigger("checkForNewline");
   }
  }).on("click checkForNewline", function(evt){
    var jqElem = $(this);
//fieldSelection plugin call
    var range = jqElem.getSelection();
    if(range["row"] && range["row"] !== currentLine){
      currentLine = range["row"];
      jqElem.trigger("newline");
   }else{
      var handTypedNewlines = jqElem.val().split(/\r\n|\r|\n/);
      var userTypedRowcounts = Math.floor(wholeString.length / jqElem.cols) + (handTypedNewlines instanceof 'object')?handTypedNewlines.length:0;
      if(userTypedRowcounts != currentLine){
         currentLine = userTypedRowcounts;
         jqElem.trigger("newline");
      }
   }
  }).on("newline", function(evt){
   // do your work, caret is on a newline.
  });
});

referenced stack overflow.

reference to get .split() regex

like image 63
DefyGravity Avatar answered Oct 27 '22 11:10

DefyGravity