Quantcast
Channel: Hot Weekly Questions - Web Applications Stack Exchange
Viewing all articles
Browse latest Browse all 9626

google document replace user's selection

$
0
0

I have an app that needs to insert some text in the document either where the cursor is positioned or over the user's selection (replacing it).

The best I've come up with is:

function newElement(document, text) {// First, check if something is selected (i.e. we replace)  var selection = document.getSelection();  var cursor = document.getCursor();  if (selection) {    var rangeElements = selection.getRangeElements();    var j = 0;    for (j; j < rangeElements.length - 1; j++) {        if (!rangeElements[j].isPartial()) { // Not satisfactory but will do for now. We ignore partial elements in the selection . . .          rangeElements[j].getElement().asText().setText('');        }    }    if (rangeElements[j].isPartial()) {      var selText = rangeElements[j].getElement().asText().getText();      var element = rangeElements[j].getElement().asText().setText(selText +''+ text);    } else {      var element = rangeElements[j].getElement().asText().setText(text);}  } else {    var element = cursor.insertText(text);  }  return element;}

It's a half solution because a selection range that contains multiple elements or partial elements simply has the new text appended (my previous attempt removed the entire element even if it was only partially selected). If my code is really to replace the user's selection with the required text, what is the better way to do it?

There's another problem. While the code above deals well with inserting the text at the cursor position and half well with overwriting the user's selection, there's a third mode in which both getSelection() and getCursor() return null. At the end of paragraph elements in google docs, there is a single whitespace that is easy to select by mistake if positioning the cursor. As this 'selection' returns null, the above code throws TypeError: Cannot read property 'insertText' of null– what is the way to deal with that?


Viewing all articles
Browse latest Browse all 9626

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>