Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ContentEditable focus in Chrome/Safari

I have a contenteditable div which needs to be focussed at pageload (place cursor at the first line).

document.getElementById("editor").focus() works well in Firefox and IE, but in Chrome/Safari it just selects the entire content!

Is there a way to make this work properly?

Thanks in advance,
Shesh

like image 275
Sheshbabu Avatar asked Oct 11 '10 07:10

Sheshbabu


1 Answers

This question may no longer be relevant to the questioner but I'll answer it for future readers. The basic principle is to set the selection to a collapsed range at the start of the element.

I solved this problem by using the Rangy JS library: http://code.google.com/p/rangy

var r = rangy.createRange();
r.setStart( document.getElementById('editor'), 0 );
r.collapse(true);
rangy.getSelection().setSingleRange(r);

This might be more than is necessary but it definitely works cross-browser and Rangy provides a bunch of extra utilities as well so it's probably worth looking into :)

like image 56
Altreus Avatar answered Nov 06 '22 02:11

Altreus