not_a_generic_user not_a_generic_user - 4 months ago 25
jQuery Question

Cursor returns to start of contenteditable Div when removing last character

For various reasons I decided to use contenteditable DIV instead of standard form elements, but I ran into a problem. Using Jquery, I'm trying to prevent the div from exceeding the maximum length.

The code works well enough, but when I clip the last character, the cursor returns to the first character in the string. The result is that if someone types past the maximum character point, the string starts to append the new characters typed and truncate what was already there one keystroke at a time.

This is the jquery I'm using:

$('.textarea_text').on('keyup',function() {
var remaining = $(this).data('max') - $(this).html().length;
if (remaining <0)
{
$(this).html($(this).html().slice(0,-1)); // Remove the last character
remaining=0;
}
$(this).closest('.textarea_area').find('.textarea_counter').html("("+remaining+" characters remaining)");
});


JSfiddle: https://jsfiddle.net/cLz7034v/14/

Answer

Do not change user input. Just do not allow to enter more characters.

$('.textarea_text').on('keydown',function(e) {//keydown instead of keyup
    var remaining = $(this).data('max') - $(this).html().length;
    $(this).closest('.textarea_area').find('.textarea_counter').html("("+remaining+" characters remaining)");
    //console.log(e.which);
    var allowedKeys=[8,35,36,37,38,39,40,46]; //arrows, home, end, del, backspace
    if (remaining <=0 && allowedKeys.indexOf(e.which) == -1)
       return false;
});