1

I want to limit the character count in my contenteditible div in vanilla JavaScript. I followed this post. But when the character limit is reached - you then can't delete the letters and start typing again. Please can anyone advise how to amend this code and explain why that is happening?

Javascript - How to limit character in a contentEditable div?

It's for a website where you can play with the type in the box so I want it to be easily editable.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
CopyV
  • 11
  • 2

1 Answers1

0

You can set the currentChars with the length of the target element text content with currentChars = event.target.textContent.length with each key press.

let maxChars = 10;
let currentChars = 0;

function checkLength(event) {
  currentChars = event.target.textContent.length
  if(currentChars >= maxChars) {
    alert('reached max chars');
    event.preventDefault();
  }
}
div {
    height: 100px;
    width: 300px;
    border: 1px solid grey;
    outline: 0;
}
<div contenteditable="true" onkeypress="checkLength(event)"></div>
<span></span>
Mina
  • 14,386
  • 3
  • 13
  • 26