Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the caret position on an editable iframe?

I need to set the caret position on a contentEditable iframe. It needs to work on Google Chrome and Firefox (no need for IE).

How can I do that?

I've tried

var ifr = document.querySelector(".myIframe");
var idoc = ifr.contentDocument;
var ibody = ifr.contentDocument.body; // content: "teststring|"

var caret = 2;

var sel = ifr.contentDocument.getSelection();
var range = sel.getRangeAt(0);

var el = ibody;
range.setStart(el, caret);
range.setEnd(el, caret);

And nothing happens on Chrome... What do I have to change?

like image 291
BrunoLM Avatar asked Feb 01 '26 05:02

BrunoLM


1 Answers

This should work:

var ifr = document.querySelector(".myIframe");
var idoc = ifr.contentDocument;
var ibody = ifr.contentDocument.body; // content: "teststring|"

var caret = 2;

var sel = ifr.contentDocument.getSelection();
var range = sel.getRangeAt(0);

var el = ibody;
range.setStart(el, caret);
range.setEnd(el, caret);

sel.removeAllRanges();
sel.addRange(range);

Look at the last two lines

like image 190
JCOC611 Avatar answered Feb 03 '26 19:02

JCOC611