Travis L
Travis L

Reputation: 681

jQuery on "enter key" create content editabledom element and select it

$(document).ready(function(){
    $( "p[contenteditable]" ).on( "keypress", function(e) {
        var code = e.keyCode;
        if(code == 13) { //Enter key
            $(this).after('<p class="new" [contenteditable]>hi</p>');
            $('p.new').css("color","red").focus();
            e.preventDefault();
        }
    });
});

See this fiddle: http://jsfiddle.net/tehtrav/T2U9M/

I'm trying to create a new <p contenteditable></p> when the enter key is pressed and change focus to it, but the focus doesn't seem to trigger. It works if I set the focus to an element other than the new paragraph (see this fiddle), but not if I call focus on the newly created paragraph.

Any ideas?

Upvotes: 0

Views: 116

Answers (1)

William Newby
William Newby

Reputation: 621

When I use your code but take the brackets our of the creation of the new paragraph, it works

$(document).ready(function(){
    $( "p[contenteditable]" ).on( "keypress", function(e) {
        var code = e.keyCode;
        if(code == 13) { //Enter key
            $(this).after('<p class="new" contenteditable>hi</p>');
            $('p.new').css("color","red").focus();
            e.preventDefault();
        }
    });
});

Upvotes: 1

Related Questions