Gjert
Gjert

Reputation: 1067

Failed to execute 'getRangeAt' on 'Selection': 0 is not a valid index

I have this problem with Chrome and Safari (works in Mozilla and IE + Edge). I want to store the caret position and selection using range=sel.getRangeAt(0);

However, I get the following error in Chrome: Uncaught IndexSizeError: Failed to execute 'getRangeAt' on 'Selection': 0 is not a valid index.

How can I fix this in another way than the following: here.

This is my fiddle

The reason why I can't use this method is because I display a hidden div, and insert text into an <input type="text"> field, I then insert that into a contenteditable div. Selecting this input field makes me save a new selection, and messes up the insert.

Here are some images to display the problem:

Part 1: The contenteditable div fields Part 1, the table Part 2: The hidden div that is displayed, and typing, changing the carter position Part 2, Typing in the URL that gets added. Part 3: On insert, console error in Chrome and Safari Part 3, The Error Code

Any suggestions?

Upvotes: 4

Views: 7209

Answers (1)

Arturas Tamulaitis
Arturas Tamulaitis

Reputation: 412

Ok so i`ve found a mistake in your code, and it was pretty simple, though hard to find :)

Issue:

Line 46/72: bE1.focus() does not work therefore object Selection.range does not exist. I`ve did simple check by calling console.log(document.activeElement) to check which element is active in page, and that was wrong element.

Solution:

Changed bE1.focus() --> div_new_1.focus()

Working example: jsFiddle

Functions i`ve changed:

function lrestoreRangePosition1() {
  closePopupLink1();
  div_new_1.focus();
  var sel = window.getSelection(),
    range = sel.getRangeAt(0);
  var x, C, sC = bE1,
    eC = bE1;

  C = rp.sC;
  x = C.length;
  while (x--) sC = sC.childNodes[C[x]];
  C = rp.eC;
  x = C.length;
  while (x--) eC = eC.childNodes[C[x]];

  range.setStart(sC, rp.sO);
  range.setEnd(eC, rp.eO);
  sel.removeAllRanges();
  sel.addRange(range)
}

function lrestoreRangePositionInsert1() {
  var newText1 = document.getElementById('url_title1').value;
  var newText2 = document.getElementById('url_content1').value;

  var pasteText = "<a href='" + newText2 + "'>" + newText1 + "</a>";
  closePopupLink1();

  div_new_1.focus();
  console.log(document.activeElement)
  var sel = window.getSelection(),
    range = sel.getRangeAt(0);
  var x, C, sC = bE1,
    eC = bE1;

  C = rp.sC;
  x = C.length;
  while (x--) sC = sC.childNodes[C[x]];
  C = rp.eC;
  x = C.length;
  while (x--) eC = eC.childNodes[C[x]];

  range.setStart(sC, rp.sO);
  range.setEnd(eC, rp.eO);
  sel.removeAllRanges();
  sel.addRange(range);

  pasteHtmlAtCaret(pasteText);
}

Let me know if that helps:)

Upvotes: 5

Related Questions