Reputation: 183
So I had to make a Quill interface for an asignmment. There must be a counter for words but I've found out that I also need a counter for all characters. So what's the best way to add this character counter to my project.
class Counter {
constructor(quill, options) {
this.quill = quill;
this.options = options;
this.container = document.querySelector(options.container);
quill.on('text-change', this.update.bind(this));
this.update(); // Account for initial contents
}
calculate() {
let text = this.quill.getText();
if (this.options.unit === 'word') {
text = text.trim();
// Splitting empty text returns a non-empty array
return text.length > 0 ? text.split(/\s+/).length : 0;
} else {
return text.length;
}
}
update() {
var length = this.calculate();
var label = this.options.unit;
if (length !== 1) {
label += 's';
}
this.container.innerText = length + ' ' + label;
}
}
Quill.register('modules/counter', Counter);
var quill = new Quill('#editor', {
modules: {
toolbar: toolbarOptions,
counter: {
container: '#counter',
unit: 'word'
}
},
theme: 'snow'
});
Upvotes: 1
Views: 8191
Reputation: 1894
quill.on('text-change', function () {
const limted = 10;
const totalChar = quillEditor.getLength() - 1;
if (quillEditor.getLength() > limted + 1)
quillEditor.deleteText(limted, totalChar);
else
chCounter.text(totalChar)
});
Upvotes: 0
Reputation: 663
In the example, https://codepen.io/anon/pen/vPRoor.
The character count starts with 1 by default. Instead, it should start with 0. This can be done by adding trim method in calculate function.
Change:
calculate() {
let text = this.quill.getText();
To:
calculate() {
let text = this.quill.getText().trim();
Upvotes: 0
Reputation: 1882
The guide has a tutorial for writing a module that counts words or characters based on config option: https://quilljs.com/guides/building-a-custom-module/#using-options
var quill = new Quill('#editor', {
modules: {
counter: {
container: '#counter',
unit: 'character'
}
}
});
Demo: https://codepen.io/anon/pen/vPRoor
Upvotes: 2