How can I add a new format (<hr> tag) to Quill.js?
I have still no idea why the question has downvotes, but however here is the solution:
Import the embed blot - important: not "block", not "embed", "block/embed"!
var Embed = Quill.import('blots/block/embed');
Define a new class that extends that Embed
class Hr extends Embed {
static create(value) {
let node = super.create(value);
// give it some margin
node.setAttribute('style', "height:0px; margin-top:10px; margin-bottom:10px;");
return node;
}
}
Define your tag
Hr.blotName = 'hr'; //now you can use .ql-hr classname in your toolbar
Hr.className = 'my-hr';
Hr.tagName = 'hr';
Write a custom handler for the <hr> button
var customHrHandler = function(){
// get the position of the cursor
var range = quill.getSelection();
if (range) {
// insert the <hr> where the cursor is
quill.insertEmbed(range.index,"hr","null")
}
}
Register your new format
Quill.register({
'formats/hr': Hr
});
Instantiate your Editor with the right selectors in your HTML
var quill = new Quill('#editor', {
modules: {
toolbar: { container: '#toolbar-container',
handlers: {
'hr': customHrHandler
}
}
},
theme: 'snow'
});
The HTML part remains the same. The whole <hr> functionality can be done similar to the <img> format.
Thank you, you helpful community.
Not enough rep to comment, so posting as an answer, to address a minor issue.
The default prompt box caused by the embed shown in @Suisse's great answer has to be seemingly handled in a toolbar handler (with a second parameter), like so:
var toolbarOptions = {
handlers: {
// ...
'hr': function(value) {
this.quill.format('hr', true);
}
}
}
Source discussion -
Documentation: How to avoid default 'prompt' when invoking custom Embed blots via toolbar module
Prompt example in Toolbar Handler docs: https://quilljs.com/docs/modules/toolbar/#handlers