Search code examples
javascriptjquerykeypresscontenteditable

jQuery / Contenteditable - new paragraph on keypress works on original but not generated content


I have some contenteditable paragraphs and have written up some jquery to generate a new paragraph when the enter key is pressed.

$('p[contenteditable="true"]').keypress(function(e) {
    if(e.which == 13) {
        e.preventDefault();
        $(this).after('<p contenteditable = "true">New Paragraph</p>');
        $(this).next('p').focus();
    }
});

This works perfectly well for all paragraphs that existed on page load. It however doesn't work at all for the newly generated paragraphs. How can I get this working on the generated paragraphs as well as the original?

http://jsfiddle.net/UU4Cg/1/


Solution

  • For dynamic content use .on

    $(document).on('keypress', 'p[contenteditable="true"]', function(e) {
        //code here
    });