2

I have the following code that focuses on the previous paragraph once current paragraph is deleted.

$(document).on('keyup', 'p[contenteditable="true"]', function(e) {
    if(e.which == 13) {
        e.preventDefault();
        $(this).after('<p contenteditable = "true">New Paragraph</p>');
        $(this).next('p').focus();
    } else if((e.which == 8 || e.which == 46) && $(this).text() == "") {
        e.preventDefault();
        var prev = $(this).prev('p');
        $(this).remove();
        prev.focus();
    };
});

However it always moves the cursor to the start of the paragraph. Is it possible to move the cursor to the end?

http://jsfiddle.net/UU4Cg/6/

Ryan King
  • 3,538
  • 12
  • 48
  • 72

1 Answers1

1

Took the function from this fine stack answer, this seems to work for me: How to move cursor to end of contenteditable entity

function setEndOfContenteditable(contentEditableElement)
{
    var range,selection;
    if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
    {
        range = document.createRange();//Create a range (a range is a like the selection but invisible)
        range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
        range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
        selection = window.getSelection();//get the selection object (allows you to change selection)
        selection.removeAllRanges();//remove any selections already made
        selection.addRange(range);//make the range you have just created the visible selection
    }
    else if(document.selection)//IE 8 and lower
    { 
        range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
        range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
        range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
        range.select();//Select the range (make it the visible selection
    }
}

$(document).on('keyup', 'p[contenteditable="true"]', function(e) {
    if(e.which == 13) {
        e.preventDefault();
        $(this).after('<p contenteditable = "true">New Paragraph</p>');
        $(this).next('p').focus();
    } else if((e.which == 8 || e.which == 46) && $(this).text() == "") {
        e.preventDefault();
        var prev = $(this).prev('p');
        $(this).remove();
        prev.focus();
        setEndOfContenteditable(prev.get(0));
    };
});
Community
  • 1
  • 1
bruchowski
  • 5,043
  • 7
  • 30
  • 46
  • Would it be possible to modify this to accept an index rather than always returning to the end? Something like `setEndOfContenteditable(prev.get(0), 3)` would move the cursor to position 3 in the paragraph. – Ryan King Apr 18 '13 at 22:55