Patrick Hendron
Patrick Hendron

Reputation: 43

Move cursor to next contentEditable - JQuery

what I am looking to do specifically is when i press enter it creates a new paragraph the cursor then moves to or selects the new content editable paragraph to begin typing but i cant seem to find a way to do it.

/*HTML Layout*/
<div id="wrap" contenteditable="true">
|| <----cursor posiiton
//*New paragraph content editable when enter is pressed
<p contenteditable="true">New Paragrpah</p>
</div>

/* JQuery Code */
if(event.which == 13){
event.preventDefault();
elem.append('<p>insert a new paragraph</p>');
$('#container *').attr('contenteditable','true');
$('p', elem).focus();}

anyone have any insight? would be much appreciated.

I know it is Possible to do it with and input field and .focus() But that wont work on a contentEditable there has to be a way of doing it.

Best Regards Patrick

Upvotes: 4

Views: 3737

Answers (1)

Niklas
Niklas

Reputation: 30002

Disable the parent contenteditable, set focus on new contenteditable, enable parent contenteditable and focus back on parent contenteditable (won't allow you to move outside of the current one otherwise in some browsers.).

$(window).keydown(function(event){

if(event.which == 13){

    event.preventDefault();

    var p = $('<p />').text("insert a new paragraph").attr('contenteditable','true').appendTo($('#wrap'));
   $('#wrap').attr('contenteditable','false');
   $(p).focus();
   $('#wrap').attr('contenteditable','true').focus();  

}

});

Example: http://jsfiddle.net/niklasvh/6AsHq/

Upvotes: 3

Related Questions