Nitish Borade Nitish Borade - 1 year ago 145
Java Question

How to setcursor position in GWT RichTextArea

Is there a way to set the cusror position in GWT RichTextArea. There is method setCusrorPosition() to do so in TextArea, but not in RichTextArea.
Perhaps there is a native JavaScript (called from GWT) that could set the cursor position in the RichTextArea?

Answer Source

You are right RichTextArea is not providing the setSelectionRange method, but i have created one using the 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
        } else {
            if (selection.removeAllRanges) { // Safari, Google Chrome
    } catch (e) {

For using above method write below code:

final RichTextArea tr = new RichTextArea();
    Button b = new Button("Test");
    b.addClickHandler(new ClickHandler() {

        public void onClick(ClickEvent event) {
            setSelectionRange(tr.getElement(), 15, 20);

Note: Do remember to put the validation checks of "pos" and "length" you are passing in setSelectionRange() method. This code had been tested in IE9, FF, Chrome.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download