3

Does anybody have workable solution to get or set cursor position in contenteditable div with elements inside? What I going to do is to create twitter-like field where I will insert on @ sign pressed. Problem is that browsers are pretty buggy with contenteditable attribute, so I cant rely on them for insert. So my algorithm is:

  • When @ pressed
  • GetCursorPos
  • get content of div as a string, split it to two halves
  • Insert string with span between halves
  • Do $(div).html(new_content) - cursor will be dropped to beginning
  • move cursor to old_cursor + span's text length

Problem with 2 and 5. I checked following questions:

And many more... There is NO workable solution (FF, Chrome, IE) for setCursorPos(elem, pos) - everywhere is move to the end or save and restore. Also I have getCursorPosition, but sometimes in chrome it gives incorrect results, so this function appreciated also!

Thanks a lot!

Community
  • 1
  • 1
Sergey Yarotskiy
  • 517
  • 4
  • 14
  • Have you checked what TinyMCE and others do for this? – NoBugs Mar 21 '14 at 13:33
  • Yes, but there are too much logic for me, I spend already two days for learning all that, this is third day. I have code that works in chrome pretty well, but ONLY in chrome. – Sergey Yarotskiy Mar 21 '14 at 13:34
  • Here is what I have so far http://jsfiddle.net/vdhm4/ (press @ to insert node + try backspace to remove node) – Sergey Yarotskiy Mar 21 '14 at 13:37
  • 1
    How about http://stackoverflow.com/a/13950376/96100 or http://stackoverflow.com/a/16100733/96100? – Tim Down Mar 22 '14 at 09:42
  • I have no chance to check them right now, but at first look they looks pretty well both. Don't know why I didn't pick them up, maybe because I tried too much and there is a mess in my head. Any way I will try them in next 3 days and will post answer here. Thanks, Tim! – Sergey Yarotskiy Mar 24 '14 at 13:27

0 Answers0