### Full Toolbar Configuration Example
Source: https://quilljs.com/docs/modules/toolbar
A comprehensive example demonstrating various control types and theme-based defaults.
```javascript
const toolbarOptions = [
['bold', 'italic', 'underline', 'strike'], // toggled buttons
['blockquote', 'code-block'],
['link', 'image', 'video', 'formula'],
[{ 'header': 1 }, { 'header': 2 }], // custom button values
[{ 'list': 'ordered'}, { 'list': 'bullet' }, { 'list': 'check' }],
[{ 'script': 'sub'}, { 'script': 'super' }], // superscript/subscript
[{ 'indent': '-1'}, { 'indent': '+1' }], // outdent/indent
[{ 'direction': 'rtl' }], // text direction
[{ 'size': ['small', false, 'large', 'huge'] }], // custom dropdown
[{ 'header': [1, 2, 3, 4, 5, 6, false] }],
[{ 'color': [] }, { 'background': [] }], // dropdown with defaults from theme
[{ 'font': [] }],
[{ 'align': [] }],
['clean'] // remove formatting button
];
const quill = new Quill('#editor', {
modules: {
toolbar: toolbarOptions
},
theme: 'snow'
});
```
--------------------------------
### Initialize Quill with Syntax Module
Source: https://quilljs.com/docs/modules/syntax
Basic setup to enable the syntax module and the code-block toolbar button.
```javascript
```
--------------------------------
### npm: Install Quill
Source: https://quilljs.com/docs/installation
Command to install Quill version 2.0.3 using npm. This is recommended for projects using bundlers.
```bash
npm install quill@2.0.3
```
--------------------------------
### Include Quill Stylesheet
Source: https://quilljs.com/docs/quickstart
Include the Quill stylesheet for the desired theme. This example uses the 'snow' theme.
```html
```
--------------------------------
### once Method
Source: https://quilljs.com/docs/api
Adds a handler that will be called only once for a specific event emission. Useful for setup tasks that only need to run on the first occurrence of an event.
```APIDOC
## once Method
### Description
Adds handler for one emission of an event. See text-change or selection-change for more details on the events themselves.
### Methods
```javascript
once(name: string, handler: Function): Quill
```
### Examples
```javascript
quill.once('text-change', () => {
console.log('First text change!');
});
```
```
--------------------------------
### dangerouslyPasteHTML Usage Example
Source: https://quilljs.com/docs/modules/clipboard
Shows how to insert an HTML snippet at a specific index in the editor.
```javascript
quill.setText('Hello!');
quill.clipboard.dangerouslyPasteHTML(5, ' World');
// Editor is now '
Hello World!
';
```
--------------------------------
### Basic Word Counter Module
Source: https://quilljs.com/docs/guides/building-a-custom-module
A simple example of a word counter module for Quill. It listens for text changes and updates a counter element.
```html
0
```
```javascript
var Quill = require('quill');
var options = {
modules: {
counter: true
}
};
var editor = new Quill('#editor', options);
var counter = document.querySelector('#counter');
editor.on('text-change', function(delta, oldDelta, source) {
if (source == 'api') {
console.log('An API call caused the change.');
} else if (source == 'user') {
counter.innerHTML = editor.getLength() - 1; // -1 for the newline character
}
});
```
--------------------------------
### Retain Operation Example
Source: https://quilljs.com/docs/guides/designing-the-delta-format
Illustrates the use of the 'retain' operation to keep characters as they are, combined with formatting and insertion.
```javascript
// Starting with "HelloWorld",
// bold "Hello", and insert a space right after it
const change = [
{ format: true, attributes: { bold: true } }, // H
{ format: true, attributes: { bold: true } }, // e
{ format: true, attributes: { bold: true } }, // l
{ format: true, attributes: { bold: true } }, // l
{ format: true, attributes: { bold: true } }, // o
{ insert: ' ' },
{ retain: true }, // W
{ retain: true }, // o
{ retain: true }, // r
{ retain: true }, // l
{ retain: true } // d
]
```
--------------------------------
### Line Formatting Example
Source: https://quilljs.com/docs/guides/designing-the-delta-format
Illustrates how line formatting attributes like alignment are handled in Delta, particularly concerning newline characters.
```javascript
const content = [
{ text: "Hello", attributes: { align: "center" } },
{ text: "\nWorld" }
];
```
```javascript
const content = [
{ text: "Hello", attributes: { align: "center" } },
{ text: "World" }
];
```
```javascript
const content = [
{ text: "HelloWorld" }
];
```
```javascript
const content = [
{ text: "Hello", attributes: { align: "center" } },
{ text: "\n" },
{ text: "World", attributes: { align: "right" } }
];
```
```javascript
// Hello World on two lines
const content = [
{ text: "Hello" },
{ text: "\n", attributes: { align: "center" } },
{ text: "World" },
{ text: "\n", attributes: { align: "right" } } // Deltas must end with newline
];
```
--------------------------------
### Embedded Content Examples
Source: https://quilljs.com/docs/guides/designing-the-delta-format
Demonstrates how to represent embedded content like images and formulas within the Delta format.
```javascript
const img = {
image: {
url: 'https://quilljs.com/logo.png'
}
};
const f = {
formula: 'e=mc^2'
};
```
```javascript
const content = [{
insert: 'Hello'
}, {
insert: 'World',
attributes: { bold: true }
}, {
insert: {
image: 'https://exclamation.com/mark.png'
},
attributes: { width: '100' }
}];
```
--------------------------------
### Initialize Quill in Read-Only Mode
Source: https://quilljs.com/docs/configuration
Configure Quill to be read-only, disabling user input and hiding the toolbar. This example also sets initial content with bold formatting.
```javascript
const options = {
readOnly: true,
modules: {
toolbar: null
},
theme: 'snow'
};
const quill = new Quill('#editor', options);
const Delta = Quill.import('delta');
quill.setContents(
new Delta()
.insert('Hello, ')
.insert('World', { bold: true })
.insert('
')
);
```
--------------------------------
### Scroll Editor to Specific Bounds
Source: https://quilljs.com/docs/api
Scrolls the editor to reveal a specific range. This example demonstrates scrolling to a given text range after initializing the editor and setting its text.
```javascript
// Scroll the editor to reveal the range of { index: 20, length: 5 }
const bounds = this.selection.getBounds(20, 5);
if (bounds) {
quill.scrollRectIntoView(bounds);
}
```
--------------------------------
### Formatting Text
Source: https://quilljs.com/docs/guides/designing-the-delta-format
Example of how to specify text formatting in a Delta, including merging attributes and removing formatting with null.
```javascript
const delta = [{
format: {
index: 4,
length: 1
},
attributes: {
bold: true
}
}];
```
--------------------------------
### Delete Operation Example
Source: https://quilljs.com/docs/guides/designing-the-delta-format
Shows how to represent the deletion of text or embeds using the 'delete' operation in a Delta.
```javascript
const delta = [{
delete: {
index: 4,
length: 1
}
}, {
delete: {
index: 12,
length: 3
}
}];
```
--------------------------------
### Basic Delta Structure with Text and Bold Attribute
Source: https://quilljs.com/docs/guides/designing-the-delta-format
An example demonstrating the basic structure of a Delta, representing plain text and formatted text (bold).
```javascript
const content = [
{ text: 'Hello' },
{ text: 'World', bold: true }
];
```
--------------------------------
### Scroll Editor to Line
Source: https://quilljs.com/docs/api
Scrolls the editor to make a specific line visible. This example sets up a Quill editor with multiple lines of text and then scrolls to display 'line 50'.
```javascript
let text = "";
for (let i = 0; i < 100; i += 1) {
text += `line ${i + 1}\n`;
}
const quill = new Quill('#editor', { theme: 'snow' });
quill.setText(text);
const target = 'line 50';
const bounds = quill.selection.getBounds(
text.indexOf(target),
target.length
);
if (bounds) {
quill.scrollRectIntoView(bounds);
}
```
--------------------------------
### Add Toolbar Handler Post Initialization in QuillJS
Source: https://quilljs.com/docs/modules/toolbar
Add custom handlers to an existing QuillJS editor instance after initialization. This example demonstrates how to add an 'image' handler using the toolbar module.
```javascript
// Handlers can also be added post initialization
const toolbar = quill.getModule('toolbar');
toolbar.addHandler('image', showImageUI);
```
--------------------------------
### Example of Non-Compact Delta (Invalid)
Source: https://quilljs.com/docs/guides/designing-the-delta-format
Illustrates a Delta that is not compact, showing how plain text segments could be unnecessarily split.
```javascript
const content = [
{ text: 'Hel' },
{ text: 'lo' },
{ text: 'World', attributes: { bold: true } }
];
```
--------------------------------
### Adding Font Styling for Custom Fonts
Source: https://quilljs.com/docs/customization
Add CSS rules to style the custom fonts registered in the font whitelist. This example shows how to add styling for the 'Roboto' font.
```html
```
--------------------------------
### Define Custom Toolbar Handlers in QuillJS
Source: https://quilljs.com/docs/modules/toolbar
Customize toolbar behavior by defining custom handler functions for specific formats. This example shows how to create a custom handler for the 'link' format, which prompts the user for a URL.
```javascript
const toolbarOptions = {
handlers: {
// handlers object will be merged with default handlers object
link: function (value) {
if (value) {
const href = prompt('Enter the URL');
this.quill.format('link', href);
} else {
this.quill.format('link', false);
}
}
}
};
const quill = new Quill('#editor', {
modules: {
toolbar: toolbarOptions
}
});
```
--------------------------------
### Delta Object Example
Source: https://quilljs.com/docs/guides/designing-the-delta-format
An example of a Delta object, which contains an array of operations.
```javascript
const delta = {
ops: [{
insert: 'Hello'
}, {
insert: 'World',
attributes: { bold: true }
}, {
insert: {
image: 'https://exclamation.com/mark.png'
},
attributes: { width: '100' }
}]
};
```
--------------------------------
### npm: Import Delta and Formats
Source: https://quilljs.com/docs/installation
Demonstrates importing Delta and specific formats like Link when using Quill via npm. This is an alternative to Quill.import().
```javascript
import Quill from 'quill';
// Or if you only need the core build
// import Quill from 'quill/core';
import { Delta } from 'quill';
// Or if you only need the core build
// import { Delta } from 'quill/core';
// Or const Delta = Quill.import('delta');
import Link from 'quill/formats/link';
// Or const Link = Quill.import('formats/link');
```
--------------------------------
### Register Formats
Source: https://quilljs.com/docs/registries
Example of registering formats for a custom registry.
```html
```
--------------------------------
### Configure Syntax Module with npm
Source: https://quilljs.com/docs/modules/syntax
Pass the highlight.js instance directly to the syntax module when using npm imports.
```javascript
import Quill from 'quill';
import hljs from 'highlight.js';
const quill = new Quill('#editor', {
modules: {
syntax: { hljs },
},
});
```
--------------------------------
### Include Quill Core CSS and JS
Source: https://quilljs.com/docs/guides/cloning-medium-with-parchment
Add the necessary CDN links for Quill core CSS and JavaScript to your HTML file. This is the first step to initializing Quill.
```html
```
--------------------------------
### CDN: Initialize Core Build Editor
Source: https://quilljs.com/docs/installation
JavaScript code to initialize a Quill editor using the core build from CDN. No theme is applied by default.
```javascript
const quill = new Quill('#editor');
```
--------------------------------
### Quill.import
Source: https://quilljs.com/docs/api
Static method returning Quill library, format, module, or theme. In general the path should map exactly to Quill source code directory structure. Unless stated otherwise, modification of returned entities may break required Quill functionality and is strongly discouraged.
```APIDOC
## Quill.import
### Description
Static method returning Quill library, format, module, or theme. In general the path should map exactly to Quill source code directory structure. Unless stated otherwise, modification of returned entities may break required Quill functionality and is strongly discouraged.
### Method
`Quill.import(path): any`
### Examples
```javascript
const Parchment = Quill.import('parchment');
const Delta = Quill.import('delta');
const Toolbar = Quill.import('modules/toolbar');
const Link = Quill.import('formats/link');
// Similar to ES6 syntax `import Link from 'quill/formats/link';`
```
### Note
Don't confuse this with the `import` keyword for ECMAScript modules. `Quill.import()` doesn't load scripts over the network, it just returns the corresponding module from the Quill library without causing any side-effects.
```
--------------------------------
### Import Quill Modules and Formats
Source: https://quilljs.com/docs/api
Returns a specified module, format, or theme from the Quill library. The path should generally match the library's directory structure.
```javascript
const Parchment = Quill.import('parchment');
const Delta = Quill.import('delta');
const Toolbar = Quill.import('modules/toolbar');
const Link = Quill.import('formats/link');
// Similar to ES6 syntax `import Link from 'quill/formats/link';`
```
--------------------------------
### Insert Formatted Text
Source: https://quilljs.com/docs/api
Inserts text into the editor with specific formatting applied. This example shows inserting bold text.
```javascript
quill.insertText(0, 'Hello', 'bold', true);
```
--------------------------------
### npm: Import Full or Core Build
Source: https://quilljs.com/docs/installation
Import Quill into your project using npm. Choose 'quill' for the full build or 'quill/core' for the core build.
```javascript
import Quill from 'quill';
// Or if you only need the core build
// import Quill from 'quill/core';
const quill = new Quill('#editor');
```
--------------------------------
### Keyboard Configuration
Source: https://quilljs.com/docs/modules/keyboard
Configuring custom key bindings during Quill initialization to override defaults or add new functionality.
```APIDOC
## Keyboard Configuration
### Description
Define custom bindings within the Quill configuration object. Bindings defined here run before Quill's default bindings, allowing for overrides.
### Request Body
- **bindings** (object) - Required - A map of binding names to configuration objects containing `key`, `handler`, and optional `context` constraints.
```
--------------------------------
### Initialize Quill with CSS Selector
Source: https://quilljs.com/docs/configuration
Instantiate Quill by providing a CSS selector for the editor's container element. Quill will use the first matching element.
```javascript
const quill = new Quill('#editor'); // First matching element will be used
```
--------------------------------
### Get an Editor Module
Source: https://quilljs.com/docs/api
Retrieves a specific module that has been added to the Quill editor instance. This is useful for accessing functionality like the toolbar.
```javascript
const toolbar = quill.getModule('toolbar');
```
--------------------------------
### Configure History Module
Source: https://quilljs.com/docs/modules/history
Initialize the Quill editor with custom history settings including delay, stack size, and user-only constraints.
```javascript
const quill = new Quill('#editor', {
modules: {
history: {
delay: 2000,
maxStack: 500,
userOnly: true
},
},
theme: 'snow'
});
```
--------------------------------
### Get Selection Bounds
Source: https://quilljs.com/docs/api
Retrieves the pixel position and dimensions of a selection at a given index. Useful for positioning tooltips relative to the editor.
```javascript
quill.setText('Hello\nWorld\n');
quill.getBounds(7); // Returns { height: 15, width: 0, left: 27, top: 31 }
```
--------------------------------
### Include Quill Library
Source: https://quilljs.com/docs/quickstart
Include the Quill JavaScript library. Ensure this is done before initializing the editor.
```html
```
--------------------------------
### Include Syntax Highlighter Dependencies
Source: https://quilljs.com/docs/modules/syntax
Required HTML tags to include highlight.js stylesheets, the library itself, and the Quill editor files.
```html
```
--------------------------------
### Configure Toolbar with Simple Array
Source: https://quilljs.com/docs/modules/toolbar
Define toolbar controls using a flat array of format names.
```javascript
const toolbarOptions = ['bold', 'italic', 'underline', 'strike'];
const quill = new Quill('#editor', {
modules: {
toolbar: toolbarOptions
}
});
```
--------------------------------
### Get Blot Index
Source: https://quilljs.com/docs/api
Use getIndex to determine the position of a Blot within the document. This is useful for calculating offsets and understanding document structure.
```javascript
let [line, offset] = quill.getLine(10);
let index = quill.getIndex(line); // index + offset should == 10
```
--------------------------------
### Delete Text on Button Click
Source: https://quilljs.com/docs/api
An example of deleting text from the editor when a button is clicked. This demonstrates integrating text deletion with user interface events.
```javascript
const quill = new Quill('#editor', { theme: 'snow' });
document.querySelector('#deleteButton').addEventListener('click', () => {
quill.deleteText(5, 7);
});
```
--------------------------------
### Apply Bubble Theme to Quill Editor
Source: https://quilljs.com/docs/themes
Include the Bubble theme's stylesheet and initialize Quill with the 'bubble' theme. This is suitable for a tooltip-based UI.
```html
```
--------------------------------
### Quill.register
Source: https://quilljs.com/docs/api
Registers a module, theme, or format(s), making them available to be added to an editor. Can later be retrieved with `Quill.import`. Use the path prefix of `'formats/'`, `'modules/'`, or `'themes/'` for registering formats, modules or themes, respectively. For formats specifically there is a shorthand to just pass in the format directly and the path will be autogenerated. Will overwrite existing definitions with the same path.
```APIDOC
## Quill.register
### Description
Registers a module, theme, or format(s), making them available to be added to an editor. Can later be retrieved with `Quill.import`. Use the path prefix of `'formats/'`, `'modules/'`, or `'themes/'` for registering formats, modules or themes, respectively. For formats specifically there is a shorthand to just pass in the format directly and the path will be autogenerated. Will overwrite existing definitions with the same path.
### Methods
`Quill.register(format: Attributor | BlotDefinintion, supressWarning: boolean = false)`
`Quill.register(path: string, def: any, supressWarning: boolean = false)`
`Quill.register(defs: { [path: string]: any }, supressWarning: boolean = false)`
### Examples
```javascript
const Module = Quill.import('core/module');
class CustomModule extends Module {}
Quill.register('modules/custom-module', CustomModule);
```
```javascript
Quill.register({
'formats/custom-format': CustomFormat,
'modules/custom-module-a': CustomModuleA,
'modules/custom-module-b': CustomModuleB,
});
Quill.register(CustomFormat);
// You cannot do Quill.register(CustomModuleA); as CustomModuleA is not a format
```
```
--------------------------------
### Create Custom HTML Toolbar
Source: https://quilljs.com/docs/modules/toolbar
Manually define the toolbar structure in HTML and pass the selector to Quill.
```html
```
--------------------------------
### Get Editor Content as Semantic HTML
Source: https://quilljs.com/docs/api
Retrieves the editor's content formatted as semantic HTML. This is useful for exporting content to be displayed in other web applications.
```javascript
const html = quill.getSemanticHTML(0, 10);
```
--------------------------------
### Create and Configure a Custom Registry
Source: https://quilljs.com/docs/customization/registries
Instantiate a new Parchment Registry and pass it to the Quill constructor to create an editor with a custom set of formats. This allows for isolated format management.
```javascript
const registry = new Parchment.Registry();
// Register the formats that you need for the editor with `registry.register()`.
// We will cover this in more detail in the next section.
const quill = new Quill('#editor', {
registry,
// ...other options
})
```
--------------------------------
### Get Editor Contents as Delta
Source: https://quilljs.com/docs/api
Retrieves the entire content of the editor as a Delta object, including formatting. This is useful for saving or processing the editor's state.
```javascript
const delta = quill.getContents();
```
--------------------------------
### format
Source: https://quilljs.com/docs/api
Formats text at the user's current selection. If the selection length is 0, the format will be set active for the next character typed. The source can be 'user', 'api', or 'silent'.
```APIDOC
## format
### Description
Formats text at the user's current selection. If the user's selection length is 0, i.e. it is a cursor, the format will be set active, so the next character the user types will have that formatting. Source may be `"user"`, `"api"`, or `"silent"`. Calls where the `source` is `"user"` when the editor is disabled are ignored.
### Method Signature
```javascript
format(name: string, value: any, source: string = 'api'): Delta
```
### Parameters
* **name** (string) - The name of the format to apply.
* **value** (any) - The value of the format.
* **source** (string, optional) - The source of the change, defaults to 'api'.
### Examples
```javascript
quill.format('color', 'red');
quill.format('align', 'right');
```
```
--------------------------------
### History Module Configuration
Source: https://quilljs.com/docs/modules/history
Configuration options for the History module during Quill initialization.
```APIDOC
## Configuration Options
### Parameters
- **delay** (number) - Optional - Default: 1000. Changes occurring within this millisecond window are merged into a single undoable change.
- **maxStack** (number) - Optional - Default: 100. Maximum size of the undo/redo stack.
- **userOnly** (boolean) - Optional - Default: false. If true, only user-initiated changes are tracked for undo/redo.
### Request Example
const quill = new Quill('#editor', {
modules: {
history: {
delay: 2000,
maxStack: 500,
userOnly: true
}
}
});
```
--------------------------------
### Configure Quill with Options Object
Source: https://quilljs.com/docs/configuration
Initialize Quill with a comprehensive options object to customize debugging, modules, placeholder text, and theme.
```javascript
const options = {
debug: 'info',
modules: {
toolbar: true,
},
placeholder: 'Compose an epic...',
theme: 'snow'
};
const quill = new Quill('#editor', options);
```
--------------------------------
### Get Line Blot at Index
Source: https://quilljs.com/docs/api
Use getLine to find the Block Blot corresponding to a specific index and its offset within that line. This is essential for line-based formatting and operations.
```javascript
quill.setText('Hello
World!');
let [line, offset] = quill.getLine(7);
// line should be a Block Blot representing the 2nd "World!" line
// offset should be 1, since the returned line started at index 6
```
--------------------------------
### Register Multiple Definitions or a Single Format
Source: https://quilljs.com/docs/api
Registers multiple formats and modules using an object, or a single format directly. For formats, the path prefix is automatically generated.
```javascript
Quill.register({
'formats/custom-format': CustomFormat,
'modules/custom-module-a': CustomModuleA,
'modules/custom-module-b': CustomModuleB,
});
Quill.register(CustomFormat);
// You cannot do Quill.register(CustomModuleA); as CustomModuleA is not a format
```
--------------------------------
### Get Leaf Blot at Index
Source: https://quilljs.com/docs/api
Use getLeaf to retrieve the specific text or embed Blot at a given index and its offset within that leaf. This is helpful for precise text manipulation.
```javascript
quill.setText('Hello Good World!');
quill.formatText(6, 4, 'bold', true);
let [leaf, offset] = quill.getLeaf(7);
// leaf should be a Text Blot with value "Good"
// offset should be 1, since the returned leaf started at index 6
```
--------------------------------
### enable
Source: https://quilljs.com/docs/api
Sets the ability for the user to edit the editor content. It accepts an optional boolean argument. Defaults to true.
```APIDOC
## enable Editor
### Description
Set ability for user to edit, via input devices like the mouse or keyboard. Does not affect capabilities of API calls, when the `source` is `"api"` or `"silent"`.
### Method
```
enable(enabled: boolean = true);
```
### Parameters
#### Path Parameters
- **enabled** (boolean) - Optional - Determines if the editor should be enabled. Defaults to true.
### Example
```javascript
// Enables user input
quill.enable();
// Disables user input
quill.enable(false);
```
```
--------------------------------
### Get Current User Selection
Source: https://quilljs.com/docs/api
Retrieves the user's current selection range. Returns null if the editor does not have focus. Use this to determine cursor position or highlighted text.
```javascript
const range = quill.getSelection();
if (range) {
if (range.length == 0) {
console.log('User cursor is at index', range.index);
} else {
const text = quill.getText(range.index, range.length);
console.log('User has highlighted: ', text);
}
} else {
console.log('User cursor is not in editor');
}
```
--------------------------------
### Clipboard Configuration Matchers
Source: https://quilljs.com/docs/modules/clipboard
Configures custom matchers during Quill initialization.
```javascript
const quill = new Quill('#editor', {
modules: {
clipboard: {
matchers: [
['B', customMatcherA],
[Node.TEXT_NODE, customMatcherB]
]
}
}
});
```
--------------------------------
### Get Editor Length
Source: https://quilljs.com/docs/api
Retrieves the total length of the editor's content. Note that even an empty editor returns a length of 1 due to a default newline character.
```javascript
const length = quill.getLength();
```
--------------------------------
### Configure Quill Toolbar with Custom Container and Handlers
Source: https://quilljs.com/docs/modules/toolbar
Use this configuration to specify a custom container for the toolbar and define custom handlers for formatting actions like bold.
```javascript
const quill = new Quill('#editor', {
modules: {
toolbar: {
container: '#toolbar', // Selector for toolbar container
handlers: {
bold: customBoldHandler
}
}
}
});
```
--------------------------------
### Legal Delta with Mixed Content Types
Source: https://quilljs.com/docs/guides/designing-the-delta-format
An example of a Delta that might be produced by an application not carefully handling format ranges, including images, text, and videos with attributes.
```javascript
const delta = [{
insert: {
image: "https://imgur.com/"
},
attributes: {
duration: 600
}
}, {
insert: "Hello",
attributes: {
alt: "Funny cat photo"
}
}, {
insert: {
video: "https://youtube.com/"
},
attributes: {
bold: true
}
}];
```
--------------------------------
### Set Placeholder Text
Source: https://quilljs.com/docs/configuration
Initialize Quill with a placeholder message that appears when the editor is empty.
```javascript
const options = {
placeholder: 'Hello, World!',
theme: 'snow'
};
const quill = new Quill('#editor', options);
```
--------------------------------
### Initialize Quill with DOM Element
Source: https://quilljs.com/docs/configuration
Instantiate Quill by passing a direct DOM element reference for the editor's container.
```javascript
const container = document.getElementById('editor');
const quill = new Quill(container);
```
--------------------------------
### Get Lines within Range
Source: https://quilljs.com/docs/api
Use getLines to retrieve an array of Block Blots within a specified index range or a given range object. This is useful for batch operations on multiple lines.
```javascript
quill.setText('Hello
Good
World!');
quill.formatLine(1, 1, 'list', 'bullet');
let lines = quill.getLines(2, 5);
// array with a ListItem and Block Blot,
// representing the first two lines
```
--------------------------------
### Extend and Register a Custom Module
Source: https://quilljs.com/docs/modules
Extend existing modules by importing them and registering a new class. This allows overriding default behavior, such as customizing clipboard paste logic.
```javascript
const Clipboard = Quill.import('modules/clipboard');
const Delta = Quill.import('delta');
class PlainClipboard extends Clipboard {
convert(html = null) {
if (typeof html === 'string') {
this.container.innerHTML = html;
}
let text = this.container.innerText;
this.container.innerHTML = '';
return new Delta().insert(text);
}
}
Quill.register('modules/clipboard', PlainClipboard, true);
// Will be created with instance of PlainClipboard
const quill = new Quill('#editor');
```
--------------------------------
### Restrict Allowed Formats
Source: https://quilljs.com/docs/configuration
Configure Quill to only allow specific formats, such as 'italic', by passing an array of format names to the 'formats' option. This example also demonstrates setting content with allowed and disallowed formats.
```javascript
const Parchment = Quill.import('parchment');
const quill = new Quill('#editor', {
formats: ['italic'],
});
const Delta = Quill.import('delta');
quill.setContents(
new Delta()
.insert('Only ')
.insert('italic', { italic: true })
.insert(' is allowed. ')
.insert('Bold', { bold: true })
.insert(' is not.')
);
```
--------------------------------
### Find Quill or Blot Instance by DOM Node
Source: https://quilljs.com/docs/api
Use Quill.find to get the Quill instance or a Blot associated with a DOM node. The bubble parameter searches ancestors if the node itself is not directly associated with a Blot.
```javascript
const container = document.querySelector('#container');
const quill = new Quill(container);
console.log(Quill.find(container) === quill); // Should be true
quill.insertText(0, 'Hello', 'link', 'https://world.com');
const linkNode = document.querySelector('#container a');
const linkBlot = Quill.find(linkNode);
// Find Quill instance from a blot
console.log(Quill.find(linkBlot.scroll.domNode.parentElement));
```
--------------------------------
### Integrate Custom Formats with Buttons
Source: https://quilljs.com/docs/guides/cloning-medium-with-parchment
Import custom blot definitions and set up event listeners for buttons to apply bold and italic formatting using Quill's format method.
```javascript
import './formats/boldBlot.js';
import './formats/italicBlot.js';
const onClick = (selector, callback) => {
document.querySelector(selector).addEventListener('click', callback);
};
onClick('#bold-button', () => {
quill.format('bold', true);
});
onClick('#italic-button', () => {
quill.format('italic', true);
});
const quill = new Quill('#editor');
```
--------------------------------
### Quill Delta Retain and Delete Operations
Source: https://quilljs.com/docs/delta
Retain operations keep characters without modification or apply formatting changes. A null value for an attribute key removes that formatting. This example demonstrates retaining, inserting, and deleting text.
```javascript
// {
// ops: [
// { insert: 'Gandalf', attributes: { bold: true } },
// { insert: ' the ' },
// { insert: 'Grey', attributes: { color: '#cccccc' } }
// ]
// }
{
ops: [
// Unbold and italicize "Gandalf"
{ retain: 7, attributes: { bold: null, italic: true } },
// Keep " the " as is
{ retain: 5 },
// Insert "White" formatted with color #fff
{ insert: 'White', attributes: { color: '#fff' } },
// Delete "Grey"
{ delete: 4 }
]
}
```
--------------------------------
### Get Editor Text Content
Source: https://quilljs.com/docs/api
Retrieves the editor's content as a plain string. The length of the returned string may be less than the editor's total length if non-string content is present. An empty editor returns '\n'.
```javascript
const text = quill.getText(0, 10);
```
--------------------------------
### Applying Header Formatting to a Line
Source: https://quilljs.com/docs/delta
This Delta operation demonstrates line formatting by applying a header level to a specific line. It shows how an attribute associated with a newline character formats the preceding line.
```json
{
ops: [
{ insert: 'The Two Towers' },
{ insert: '\n', attributes: { header: 1 } },
{ insert: 'Aragorn sped on up the hill.\n' }
]
}
```
--------------------------------
### Get Formatting for a Range
Source: https://quilljs.com/docs/api
Retrieves common formatting for text within a specified range. If all text in the range shares a truthy value for a format, that value is returned. If values differ, an array of truthy values is returned. If no range is supplied, the user's current selection is used.
```javascript
quill.setText('Hello World!');
quill.formatText(0, 2, 'bold', true);
quill.formatText(1, 2, 'italic', true);
quill.getFormat(0, 2); // { bold: true }
quill.getFormat(1, 1); // { bold: true, italic: true }
quill.formatText(0, 2, 'color', 'red');
quill.formatText(2, 1, 'color', 'blue');
quill.getFormat(0, 3); // { color: ['red', 'blue'] }
quill.setSelection(3);
quill.getFormat(); // { italic: true, color: 'blue' }
quill.format('strike', true);
quill.getFormat(); // { italic: true, color: 'blue', strike: true }
quill.formatLine(0, 1, 'align', 'right');
quill.getFormat(); // { italic: true, color: 'blue', strike: true,
// align: 'right' }
```
--------------------------------
### Basic Text Formatting with Bold and Color
Source: https://quilljs.com/docs/delta
This Delta operation describes the string 'Gandalf the Grey' with 'Gandalf' bolded and 'Grey' colored #cccccc. It demonstrates basic text insertion and attribute application.
```json
{
ops: [
{ insert: 'Gandalf', attributes: { bold: true } },
{ insert: ' the ' },
{ insert: 'Grey', attributes: { color: '#cccccc' } }
]
}
```
--------------------------------
### Configure custom keyboard bindings during initialization
Source: https://quilljs.com/docs/modules/keyboard
Defines a set of bindings to override defaults or add new functionality, passed into the Quill configuration object.
```javascript
const bindings = {
// This will overwrite the default binding also named 'tab'
tab: {
key: 9,
handler: function() {
// Handle tab
}
},
// There is no default binding named 'custom'
// so this will be added without overwriting anything
custom: {
key: ['b', 'B'],
shiftKey: true,
handler: function(range, context) {
// Handle shift+b
}
},
list: {
key: 'Backspace',
format: ['list'],
handler: function(range, context) {
if (context.offset === 0) {
// When backspace on the first character of a list,
// remove the list instead
this.quill.format('list', false, Quill.sources.USER);
} else {
// Otherwise propogate to Quill's default
return true;
}
}
}
};
const quill = new Quill('#editor', {
modules: {
keyboard: {
bindings: bindings
}
}
});
```
--------------------------------
### Include Quill Core Stylesheet
Source: https://quilljs.com/docs/customization
Link to Quill's core CSS for basic styling. This is necessary even when using a custom theme or no theme.
```html
```
--------------------------------
### quill.keyboard.addBinding
Source: https://quilljs.com/docs/modules/keyboard
Registers a new keyboard event handler with specific key combinations and optional context constraints.
```APIDOC
## quill.keyboard.addBinding
### Description
Registers a handler for a specific key and modifier combination. Handlers are executed synchronously in the order they were bound.
### Parameters
#### Request Body
- **key** (string|array) - Required - The JavaScript event key code or string shorthand.
- **shortKey** (boolean) - Optional - Platform-specific modifier (metaKey on Mac, ctrlKey on Windows/Linux).
- **shiftKey** (boolean|null) - Optional - Whether the shift key must be active, inactive, or ignored.
- **handler** (function) - Required - The function to execute. Receives `range` and `context` as arguments.
### Request Example
```javascript
quill.keyboard.addBinding({
key: 'b',
shortKey: true
}, function(range, context) {
this.quill.formatText(range, 'bold', true);
});
```
```
--------------------------------
### CDN: Core Build Script and Stylesheet
Source: https://quilljs.com/docs/installation
Use these tags for the core build of Quill via CDN, which requires manual addition of formats and modules.
```html
```
--------------------------------
### HTML Structure for Quill Editor and Controls
Source: https://quilljs.com/docs/guides/cloning-medium-with-parchment
Set up the HTML for the editor container, custom toolbar buttons, and the main editor area. Ensure the editor div has an ID for JavaScript targeting.
```html
Tell your story...
```
--------------------------------
### Configure Quill Toolbar with Shorthand Container
Source: https://quilljs.com/docs/modules/toolbar
This shorthand allows for a more concise way to specify the toolbar's container element when no custom handlers are needed.
```javascript
const quill = new Quill('#editor', {
modules: {
// Equivalent to { toolbar: { container: '#toolbar' }}
toolbar: '#toolbar'
}
});
```
--------------------------------
### getContents
Source: https://quilljs.com/docs/api
Retrieves the entire contents of the editor as a Delta object, including formatting.
```APIDOC
## getContents
### Description
Retrieves contents of the editor, with formatting data, represented by a Delta object.
### Method Signature
```javascript
getContents(index: number = 0, length: number = remaining): Delta
```
### Example Usage
```javascript
const delta = quill.getContents();
```
```
--------------------------------
### getText
Source: https://quilljs.com/docs/api
Retrieves the editor's content as a plain string.
```APIDOC
## getText
### Description
Retrieves the string contents of the editor. Non-string content are omitted, so the returned string's length may be shorter than the editor's as returned by `getLength`. Note even when Quill is empty, there is still a blank line in the editor, so in these cases `getText` will return '\n'. The `length` parameter defaults to the length of the remaining document.
### Method Signature
```javascript
getText(index: number = 0, length: number = remaining): string
```
### Example Usage
```javascript
const text = quill.getText(0, 10);
```
```
--------------------------------
### on Method
Source: https://quilljs.com/docs/api
Adds an event handler to the Quill instance. This method allows you to subscribe to various events like `text-change` and `selection-change`.
```APIDOC
## on Method
### Description
Adds event handler. See text-change or selection-change for more details on the events themselves.
### Methods
```javascript
on(name: string, handler: Function): Quill
```
### Examples
```javascript
quill.on('text-change', () => {
console.log('Text change!');
});
```
```
--------------------------------
### Enable Quill Modules via Configuration
Source: https://quilljs.com/docs/modules
Include modules in the Quill configuration object to enable them. Some modules accept custom configuration objects, while others can be enabled with a simple boolean.
```javascript
const quill = new Quill('#editor', {
modules: {
history: { // Enable with custom configurations
delay: 2500,
userOnly: true
},
syntax: true // Enable with default configuration
}
});
```
--------------------------------
### Group Toolbar Controls
Source: https://quilljs.com/docs/modules/toolbar
Nest arrays to group controls within a ql-formats span for layout styling.
```javascript
const toolbarOptions = [['bold', 'italic'], ['link', 'image']];
```