7

How can I catch the event of "cursor place change" inside textarea with jQuery (also should working in IE6)?

Example1:

Before :text |

After : te|

Example2:

Before :text |

After : text tex|t2

Example3:

Before :text |

After : |


Edit:

After catching the event of cursor- need also to check if cursor change his position (also have to work for IE6)

Edit2:

If you have solution that will not work in IE6 but in IE7+webkit please write it

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Ben
  • 25,389
  • 34
  • 109
  • 165

2 Answers2

16

There are essentially three events that can cause a cursor to change position,

  1. keystrokes

  2. mouse clicks

  3. programmatic events like paste, select, focus...

    I would capture those events for whatever it is you are trying to accomplish with 'cursor place change'

code sample added:

$("#myTextInput").bind("keydown click focus", function() {
  alert("Current position: " + $(this).caret().start);
});

Thanks to @Nick Craver

Community
  • 1
  • 1
Cos Callis
  • 5,051
  • 3
  • 30
  • 57
  • thanks, 1. how can I detect cursor position after I catch it by event? 2. its posible to insert to $('textarea').bind('all event') but its create CPU problem - its should be insert to bind only needed events exectly – Ben Apr 29 '11 at 13:45
  • thank you, 1. its not catch "delete by the mouse" new cursor position 2. plugin to heavy 2,299 bytes – Ben Apr 29 '11 at 15:11
  • @Yosef: please explain #1? Mouse doesn't delete. You might want to add context menu action, delete, to the list of events you are capturing. as for #2, if you get the latest version of jquery (1.5.2) in the minified version, it is 83k. (you want to debug/dev against the full version and then switch to minified for deployment. How is 2.3 k "too heavy"? – Cos Callis Apr 29 '11 at 15:41
  • ok, I mean in #1 that user can delete with keyboard or with the mouse chars inside textarea - and cursor change his position.if user delete by keyboard you catch it but with the mouse you not catch with "keydown click focus". – Ben May 01 '11 at 09:22
  • @Yosef, by your description "mouse delete" should be captured as either a keydown event or a keyup. (The cursor position may be changed by the delete happening between keydown and keyup). – Cos Callis May 01 '11 at 19:42
2

I've found that the select event seems to cover all changes to caret position.

Ryder Bergerud
  • 753
  • 1
  • 6
  • 15