Search code examples
javascripthtmljquerylimitcontenteditable

How to limit number of lines in contenteditable div


I have a contenteditable div and would like to limit to a maximum number of lines, using jQuery or JS.

Edit 2: As it creates divs for new lines, how can I make it continue from the last line (limit - max line) when a text is pasted?


Solution

  • You can use jQuery to count the number of new divs created as line breaks inside your contenteditable div and remove the contenteditable property if this number reaches a given limit.

    Note: This may not work with IE because as far as I know IE uses <p> for new lines.

    HTML:

    <div id="test" contenteditable="true">--- Insert text here ---</div>
    

    jQuery:

    $(function(){
        $("#test").on("keyup", function(){
            if ($("#test div").length > 5) {
                $("#test").prop("contenteditable" , false);
            }
        });
    });