Reputation: 11
I have contenteditable div and I need to add maxlength limit to this element. It can be done simply by control keyup event but if user paste huge amount of text by ctrl+v I need to reduce user input. Also I have to be very carefull becouse it can be html. So cannot just use substring. Is there any idea how to do it ? Any help will save my life.
Upvotes: 1
Views: 3029
Reputation: 1
A very simple way to do this is by using the keyown
event and the Event object's preventDeafult()
method.
let myDiv=document.querySelector("#my_div"); //select your contentEditable div
let maxLength=12; //your maxlength chars
let specialKeys=[13,9,16,20,19,145,144,112,113,114,115,116,117,118,119,120,121,122,123,145,46,39,37,40,38,35,34,33,36,46,93,18,17,27,27,8,91]; //all especial key like f1 ... f12, Enter, Esc,etc...
myDiv.addEventListener("keydown",e=>{ //when a key is pressed inside the div
if(myDIV.textContent.length>maxLength-1 && specialKeys.indexOf(e.keyCode)<0){ //If the maxlength is exceeded and the pressed key is not a special key
e.preventDefault(); //then we lock the key
}
});
What this piece of code does is simply disable the use of the keys once the maxlength has been reached. But since we don't want to disable all the keys, we have created the specialKeys array, in which we put the codes of the keys that we don't want to disable. (such as Enter key with code = 13, esccape key, etc). As a result we only disable the keys that generate characters
Upvotes: 0
Reputation: 167
stopping pasting in the div requires control of the input event. I dont remember who here help me with this forever ago but we use this code on a couple pages.
const limit = 200;
rem = limit - $('#editor').text().length;
$("#counter").append("You have <strong>" + rem + "</strong> chars left.");
$("#editor").on('input', function () {
var char = $('#editor').text().length;
rem = limit - char;
$("#counter").html("You have <strong>" + rem + "</strong> chars left.");
console.log(char)
console.log(rem);
if (char >= 100) {
$("#counter").css("color", "#ff7777");
}
else
$("#counter").css("color", "#111111");
if(char>200)
{
//add your code to do what you want about too much text...
}
});
Im totally stealing that from someone on here. but I cant find the post.. so thank you goes out to one of you wonderful ppl.
EDIT ok got it it's from this answer on a similar post.
Upvotes: 1