3

Had a look at a few methods of moving the cursor around and cant seem to come up with a elegant / working way.

I basicly want to call a line of code to do the following psuedo code.

  1. Get length of text in editable div
  2. Set cursor to last letter

e.g.

this is sample text|

cursor set to where | is

How simple is this?

JsFiddle:http://jsfiddle.net/v8agZ/5/

Thanks

Lemex
  • 3,772
  • 14
  • 53
  • 87
  • You can use this link for an answer: http://stackoverflow.com/questions/2442460/focus-on-input-field-with-value – SRay Aug 23 '12 at 20:40

2 Answers2

1

This is a way in which you can put the cursor at the end of an editable div (adapted from this question).

HTML

<div id="mydiv">
    Lorem ipsum dolor sit amet,
    <br />
    <br />
    consectetur adipisicing elit
</div>

Javascript

function setCursorToEnd(ele) {
    var range = document.createRange();
    var sel = window.getSelection();
    range.setStart(ele, ele.childNodes.length - 1);
    range.collapse(true);
    sel.removeAllRanges();
    sel.addRange(range);
    ele.focus();
}

var mydiv = document.getElementById("mydiv");
setCursorToEnd(mydiv);

If you want to use jQuery (that is useless in this case), you can simply get the mydiv element using the $() and get() methods as follows:

var mydiv = $("#mydiv").get(0);
setCursorToEnd(mydiv);
Community
  • 1
  • 1
Vito Gentile
  • 13,336
  • 9
  • 61
  • 96
0

I think you can use jCaret plugin

A Demo , Not mine

defau1t
  • 10,593
  • 2
  • 35
  • 47