How to set cursor position in GWT RichTextArea

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

+6
source share
2 answers

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.

+1
source

Not sure if this is still required, but I tried to get this job done all day and finally was able to crack my way to a solution. This has been tested only in Chrome / Safari. Hope this helps someone.

 public static native void setCursor(Element elem, int pos, int length) /*-{ var node = elem.contentWindow.document.body; var range = elem.contentWindow.getSelection().getRangeAt(0); var treeWalker = $doc.createTreeWalker(node, NodeFilter.SHOW_TEXT, function(node) { var nodeRange = $doc.createRange(); nodeRange.selectNodeContents(node); return NodeFilter.FILTER_ACCEPT; }); var charCount = 0; while (treeWalker.nextNode()) { if (charCount + treeWalker.currentNode.length > pos) break; charCount += treeWalker.currentNode.length; } var newRange = elem.contentWindow.document.createRange(); newRange.setStart(treeWalker.currentNode, 1); newRange.setEnd(treeWalker.currentNode, 1); var selection = elem.contentWindow.getSelection(); if (selection.removeRange) { // Firefox, Opera, IE after version 9 selection.removeRange(range); } else if (selection.removeAllRanges) { // Safari, Google Chrome selection.removeAllRanges(); } selection.addRange(newRange); }-*/; 

This code was edited on November 28, 2016 to correct minor syntax errors.

+1
source

Source: https://habr.com/ru/post/926032/


All Articles