Search code examples
javascriptjquerycontenteditable

Handling copy/paste and max length using contenteditable in Jquery


Is there a proper way to handle both copy/paste and max length using contenteditable in Jquery? Currently, I am using the code below only for max length. However, if a user decided to copy paste a text that is longer than the max length allowed, the text will still go through.

Basically, my goal is to set character's limit up to 200 in length, also I want a decent way to handle if a user decided to copy paste something, especially if it is longer than the max length allowed.

$('div').keydown(function (event) {

if($(this).text().length >= 200 && event.keyCode != 8) {
      event.preventDefault();
    }

});

Solution

  • You can add a paste Event:

    $('div').on('paste', function(event) {
        // handle event
    });
    

    Read more about it in the MDN Web Docs.

    var editable = $('div');
    editable.on('paste', function(event) {
        if (editable.text().length >= 200) {
            editable.textContent = editable.text().substr(0,200); // it uses the whole content of the editable div
        }
    });