How to Use CKEditor Plugins with Metronic Bootstrap
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?
Replies (2)
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.
<pre> 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); }); }); </pre>For more info please check <a href="https://ckeditor.com/docs/">CKEditor Docs</a>.
Regards, Sean