Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript/jQuery set cursor in editable DIV

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

like image 518
Lemex Avatar asked Dec 03 '25 17:12

Lemex


1 Answers

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);
like image 58
Vito Gentile Avatar answered Dec 06 '25 07:12

Vito Gentile



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!