You're right. RichTextArea does not provide a setSelectionRange method, but I created it using JSNI.
Below is the method
public native void setSelectionRange(Element elem, int pos, int length) /*-{ try { var selection = null, range2 = null; var iframeWindow = elem.contentWindow; var iframeDocument = iframeWindow.document; selection = iframeWindow.getSelection(); range2 = selection.getRangeAt(0); //create new range var range = iframeDocument.createRange(); range.setStart(selection.anchorNode, pos); range.setEnd(selection.anchorNode, length); //remove the old range and add the newly created range if (selection.removeRange) { // Firefox, Opera, IE after version 9 selection.removeRange(range2); } else { if (selection.removeAllRanges) { // Safari, Google Chrome selection.removeAllRanges(); } } selection.addRange(range); } catch (e) { $wnd.alert(e); } }-*/;
To use the above method, write the code below:
final RichTextArea tr = new RichTextArea(); Button b = new Button("Test"); b.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { setSelectionRange(tr.getElement(), 15, 20); tr.setFocus(true); } }); RootPanel.get().add(tr); RootPanel.get().add(b);
Note. Remember to put the pos and length checks that you pass in the setSelectionRange () method. This code has been tested in IE9, FF, Chrome.
source share