2

While writing a text, a jQuery script will try and replace from time to time some words.

The text is written within a div tag with content editable set on true.

How can I focus the cursor at the end of the last span child, right before the parent span ?

<div id="cl-edit-outline-title_AtD_div" contenteditable="true">
 <span class="mceItemHidden">
  <span class="hiddenSpellError" pre="">fgsddfsdfgdsfgsd</span>
  <span class="hiddenSpellError" pre="a">a</span>
  <span class="hiddenSpellError" pre="b">b</span>
  &nbsp;
  <span class="hiddenSpellError" pre="c">c</span>
  <span class="hiddenSpellError" pre="d">d</span>
 </span>
</div>

I have searched on the web for solutions, but found none.

fiddle

Ionut Flavius Pogacian
  • 4,750
  • 14
  • 58
  • 100

1 Answers1

0
$.fn.focusEnd = function() {
    $(this).focus();
    var tmp = $('<span />').appendTo($(this)),
        node = tmp.get(0),
        range = null,
        sel = null;

    if (document.selection) {
        range = document.body.createTextRange();
        range.moveToElementText(node);
        range.select();
    } else if (window.getSelection) {
        range = document.createRange();
        range.selectNode(node);
        sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    }
    tmp.remove();
    return this;
}

To call... $('.yourClassDiv').focusEnd();

enjoy.. ;)

Fábio Zangirolami
  • 1,856
  • 4
  • 18
  • 33