.preventDefault() not working in on.('input', function{})
To answer your main question:.preventDefault()
cancel behavior of the events that are cancelable. input
event is not .
To check whether an event
is cancelable, try: console.log(event.cancelable);
.
For input
it will say "false"
You may want something like this (untested):
const limit = 10;var rem = limit - $('#About').text().length;$("#counter").append("You have <strong>" + rem + "</strong> chars left.");$("#About").on('input', function(event) { var char = $(this).text().length; rem = limit - char; if(rem <= 0){ $(this).text($(this).text().slice(0, limit)); } $("#counter").html("You have <strong>" + rem + "</strong> chars left.");});
EDIT
JSFiddle demo
Since it's contentEditable, I had to use an additional code (from this answer) to set a caret at the end of the input.
use keydown
instead of input
jQuery(document).ready(function($){ const limit = 10; rem = limit - $('#About').text().length; $("#counter").append("You have <strong>" + rem + "</strong> chars left."); $("#About").on('keypress', function(event) { var char = $('#About').text().length; if(char>limit) { return false; //or event.preventDefault(); //TODO } rem = limit - char; $("#counter").html("You have <strong>" + rem + "</strong> chars left."); });});
DEMO
el.addEventListener('input', function(event) { if ( this.innerHTML.length >300 && event.keyCode != 8) { document.execCommand("undo"); } });