Hi,
On my page, HTML textarea elements are configured to be transformed into CKEditor instances using the following code:
const textareaElements = document.querySelectorAll('[data-ckeditor="true"]');
textareaElements.forEach(el => {
ClassicEditor.create(el);
});
I want to impose a limit on the maximum number of words that can be entered. Can you please guide how to achieve that?
CKEditor plugins integrated with the Metronic Bootstrap framework enhance content editing with powerful features and a responsive design. CKEditor allows easy customization using plugins for functionalities like media best internet package embedding, code syntax highlighting, and table management. When paired with Metronic Bootstrap, these plugins ensure consistent styling, mobile responsiveness, and seamless integration into web applications, improving the user experience for content creators and developers alike.
Hi,
To impose a word limit on CKEditor instances, you can make use of CKEditor's event system to listen to the input event and apply a word count logic. CKEditor does not provide a built-in word limit feature, so you'll need to implement a custom solution to count the words and prevent further input when the limit is reached.
const textareaElements = document.querySelectorAll("[data-ckeditor="true"]");
const MAX_WORDS = 100; // Set your word limit here
textareaElements.forEach(el => {
ClassicEditor.create(el).then(editor => {
// Listen to the input event in the editor
editor.model.document.on("change:data", () => {
// Get the editor content as plain text
const text = editor.getData().replace(/<[^>]*>/g, "").trim();
// Count the number of words
const words = text.split(/\s+/).filter(word => word.length > 0);
const wordCount = words.length;
// If the word count exceeds the limit, prevent more input
if (wordCount > MAX_WORDS) {
alert(`You have reached the maximum word limit of ${MAX_WORDS} words.`);
// Optionally, trim the content to the maximum allowed number of words
const limitedText = words.slice(0, MAX_WORDS).join(" ");
// Set the truncated content back into the editor
editor.setData(limitedText);
}
});
}).catch(error => {
console.error("There was a problem initializing CKEditor:", error);
});
});
Thanks for your reply, Sean. I'll give it a try.