Pass the event
object to your function and call e.preventDefault()
if the maximum is reached:
var content_id = 'editable_div';
max = 10;
//binding keyup/down events on the contenteditable div
$('#'+content_id).keyup(function(e){ check_charcount(content_id, max, e); });
$('#'+content_id).keydown(function(e){ check_charcount(content_id, max, e); });
function check_charcount(content_id, max, e)
{
if(e.which != 8 && $('#'+content_id).text().length > max)
{
// $('#'+content_id).text($('#'+content_id).text().substring(0, max));
e.preventDefault();
}
}
Although, you may need to do a little more to allow the user to do things like ‘delete’.
Also, you could probably get rid of the keyup
handler. keydown
should be enough.