Ace code editor
Overview
Ace is an embeddable code editor written in JavaScript. It matches the features and performance of native editors such as Sublime, Vim and TextMate. It can be easily embedded in any web page and JavaScript application. Ace is maintained as the primary editor for Cloud9 IDE and is the successor of the Mozilla Skywriter (Bespin) project. Main features:
- Syntax highlighting for over 110 languages (TextMate/Sublime Text.tmlanguage files can be imported)
- Over 20 themes (TextMate/Sublime Text .tmtheme files can be imported)
- Automatic indent and outdent
- An optional command line
- Handles huge documents (four million lines seems to be the limit!)
- Fully customizable key bindings including vim and Emacs modes
- Search and replace with regular expressions
- Highlight matching parentheses
- Toggle between soft tabs and real tabs
- Displays hidden characters
- Drag and drop text using the mouse
- Line wrapping
- Code folding
- Multiple cursors and selections
- Live syntax checker (currently JavaScript/CoffeeScript/CSS/XQuery)
- Cut, copy, and paste functionality
Usage
Ace can be easily embedded into any existing web page. You can either use one of pre-packaged versions of ace (just copy one of src*
subdirectories somewhere into your project), or use requireJS to load contents of lib/ace as ace. By default the editor only supports plain text mode; many other languages are available as separate modules.
Basic markup is:
<!-- Basic markup-->
<div id="html_editor">
<!-- Default card -->
<div class="card">
<div class="card-header d-md-flex">
<h5 class="mb-0">
Card title
<span class="fw-semibold">Default</span>
<small>Full featured toolbar</small>
</h5>
</div>
<div class="card-body">
Card body
</div>
</div>
<!-- /default card -->
</div>
Initialize via JavaScript:
// HTML editor
var html_editor = ace.edit("html_editor");
html_editor.setTheme("ace/theme/monokai");
html_editor.getSession().setMode("ace/mode/html");
html_editor.setShowPrintMargin(false);
CKEditor
Overview
The rich text editor for every use case. CKEditor 5 allows users to create any type of content in your application, be it documents, reports, emails, notes or chat messages.
CKEditor 5 provides every type of WYSIWYG editing solution imaginable. From editors similar to Google Docs and Medium, to Slack or Twitter-like applications, all is possible within a single editing framework.
The editor comes with a well-designed UI and perfect UX, so users can easily manage media and tables as well as use advanced features, such as auto-formatting, mentions, Paste from Word or Markdown support.Core features are:
- Track Changes
- Comments
- Revision History
- Real-time Collaboration
- Export to PDF and Word
- Spell and grammar check
- Pagination
- Math equations
Usage
Load JavaScript file locally or from CDN:
<!-- CDN -->
<script src="https://cdn.ckeditor.com/ckeditor5/35.1.0/classic/ckeditor.js"></script>
<!-- Load locally -->
<script src="assets/js/vendor/editors/ckeditor/ckeditor_classic.js"></script>
Create textarea
or div
element:
<!-- Target element -->
<textarea class="form-control" id="ckeditor_classic_prefilled">...</textarea>
Finally, run this script after the DOM is ready:
// Editor with prefilled text
ClassicEditor.create(document.querySelector('#ckeditor_classic_prefilled'), {
heading: {
options: [
{ model: 'paragraph', title: 'Paragraph', class: 'ck-heading_paragraph' },
{ model: 'heading1', view: 'h1', title: 'Heading 1', class: 'ck-heading_heading1' },
{ model: 'heading2', view: 'h2', title: 'Heading 2', class: 'ck-heading_heading2' },
{ model: 'heading3', view: 'h3', title: 'Heading 3', class: 'ck-heading_heading3' },
{ model: 'heading4', view: 'h4', title: 'Heading 4', class: 'ck-heading_heading4' },
{ model: 'heading5', view: 'h5', title: 'Heading 5', class: 'ck-heading_heading5' },
{ model: 'heading6', view: 'h6', title: 'Heading 6', class: 'ck-heading_heading6' }
]
}
}).catch(error => {
console.error(error);
});
Documentation
CKEditor library has a very extensive documentation with lots of different examples, API reference, configuration parameters, migration guide and other services. Please refer to official CKEditor documentation for more information.
Quill editor
Overview
Quill is a free, open source WYSIWYG editor built for the modern web. With its modular architecture and expressive API, it is completely customizable to fit any need. There are many solutions to choose from, but Quill brings a few modern ideas to consider:
- API Driven Design
- Custom Content and Formatting
- Cross Platform
- Easy to Use
Usage
Load JavaScript file locally or from CDN:
<!-- CDN -->
<script src="//cdn.quilljs.com/1.3.6/quill.min.js"></script>
<!-- Load plugin -->
<script src="assets/js/vendor/editors/quill/quill.min.js"></script>
Then initialize via JavaScript:
// Initialize
const quillFull = new Quill('.quill-full', {
modules: {
toolbar: [
[{ 'font': [] }],
[{ 'size': ['small', false, 'large', 'huge'] }],
[{ 'header': [1, 2, 3, 4, 5, 6, false] }],
['bold', 'italic', 'underline', 'strike'],
['blockquote', 'code-block'],
[{ 'header': 1 }, { 'header': 2 }],
[{ 'list': 'ordered'}, { 'list': 'bullet' }],
[{ 'script': 'sub'}, { 'script': 'super' }],
[{ 'indent': '-1'}, { 'indent': '+1' }],
[{ 'direction': 'rtl' }],
[{ 'color': [] }, { 'background': [] }],
[{ 'align': [] }],
[ 'formula', 'image', 'video' ],
['clean']
]
},
bounds: '.content-inner',
placeholder: 'Please add your text here...',
theme: 'snow'
});
Configuration
Quill allows several ways to customize it to suit your needs. This section is dedicated to tweaking existing functionality
Container
// Option 1
var editor = new Quill('.editor'); // First matching element will be used
// Option 2
var container = document.getElementById('editor');
var editor = new Quill(container);
// Option 3
var container = $('.editor').get(0);
var editor = new Quill(container);
Options
var options = {
debug: 'info',
modules: {
toolbar: '#toolbar'
},
placeholder: 'Compose an epic...',
readOnly: true,
theme: 'snow'
};
var editor = new Quill('#editor', options);
bounds
Default: document.body
debug
Default: yarn
formats
Default: All formats
Whitelist of formats to allow in the editormodules
Default: null
Collection of modules to include and respective optionsplaceholder
Default: none
readOnly
Default: false
scrollingContainer
Default: null
overflow-y: auto
), if is has been changed from the default ql-editor
with custom CSS. Necessary to fix scroll jumping bugs when Quill is set to auto grow its height, and another ancestor container is responsible from the scrolling.
theme
Default: snow
API
Content
deleteText
"user"
, "api"
, or "silent"
. Calls where the source is "user"
when the editor is disabled are ignored.
// Methods
deleteText(index: Number, length: Number, source: String = 'api'): Delta
// Example
quill.deleteText(6, 4);
getContents
// Methods
getContents(index: Number = 0, length: Number = remaining): Delta
// Example
var delta = quill.getContents();
getLength
getLength
will return 1.
// Methods
getLength(): Number
// Example
var length = quill.getLength();
getText
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.
// Methods
getText(index: Number = 0, length: Number = remaining): String
// Example
var text = quill.getText(0, 10);
insertEmbed
"user"
, "api"
, or "silent"
. Calls where the source is "user"
when the editor is disabled are ignored.
// Methods
insertEmbed(index: Number, type: String, value: any, source: String = 'api'): Delta
// Example
quill.insertEmbed(10, 'image', 'https://quilljs.com/images/cloud.png');
insertText
"user"
, "api"
, or "silent"
. Calls where the source
is "user"
when the editor is disabled are ignored.
// Methods
insertText(index: Number, text: String, source: String = 'api'): Delta
insertText(index: Number, text: String, format: String, value: any,
source: String = 'api'): Delta
insertText(index: Number, text: String, formats: { [String]: any },
source: String = 'api'): Delta
// Examples
quill.insertText(0, 'Hello', 'bold', true);
quill.insertText(5, 'Quill', {
'color': '#ffff00',
'italic': true
});
setContents
"user"
, "api"
, or "silent"
. Calls where the source
is "user"
when the editor is disabled are ignored.
// Method
setContents(delta: Delta, source: String = 'api'): Delta
// Example
quill.setContents([
{ insert: 'Hello ' },
{ insert: 'World!', attributes: { bold: true } },
{ insert: '\n' }
]);
setText
"user"
, "api"
, or "silent"
. Calls where the source
is "user"
when the editor is disabled are ignored.
// Method
setText(text: String, source: String = 'api'): Delta
// Example
quill.setText('Hello\n');
updateContents
"user"
, "api"
, or "silent"
. Calls where the source
is "user"
when the editor is disabled are ignored.
// Method
updateContents(delta: Delta, source: String = 'api'): Delta
// Example
// Assuming editor currently contains [{ insert: 'Hello World!' }]
quill.updateContents(new Delta()
.retain(6) // Keep 'Hello '
.delete(5) // 'World' is deleted
.insert('Quill')
.retain(1, { bold: true }) // Apply bold to exclamation mark
);
// Editor should now be [
// { insert: 'Hello Quill' },
// { insert: '!', attributes: { bold: true} }
// ]
Formatting
format
"user"
, "api"
, or "silent"
. Calls where the source
is "user"
when the editor is disabled are ignored.
// Method
format(name: String, value: any, source: String = 'api'): Delta
// Examples
quill.format('color', 'red');
quill.format('align', 'right');
formatLine
false
for the value argument. The user’s selection may not be preserved. Source may be "user"
, "api"
, or "silent"
. Calls where the source
is "user"
when the editor is disabled are ignored.
// Methods
formatLine(index: Number, length: Number, source: String = 'api'): Delta
formatLine(index: Number, length: Number, format: String, value: any,
source: String = 'api'): Delta
formatLine(index: Number, length: Number, formats: { [String]: any },
source: String = 'api'): Delta
// Examples
quill.setText('Hello\nWorld!\n');
quill.formatLine(1, 2, 'align', 'right'); // right aligns the first line
quill.formatLine(4, 4, 'align', 'center'); // center aligns both lines
formatText
formatLine
helper. See formats for a list of available formats. To remove formatting, pass false for the value argument. The user’s selection may not be preserved. Source may be "user"
, "api"
, or "silent"
. Calls where the source
is "user"
when the editor is disabled are ignored.
// Method
formatText(index: Number, length: Number, source: String = 'api'): Delta
formatText(index: Number, length: Number, format: String, value: any,
source: String = 'api'): Delta
formatText(index: Number, length: Number, formats: { [String]: any },
source: String = 'api'): Delta
// Examples
quill.setText('Hello\nWorld!\n');
quill.formatText(0, 5, 'bold', true); // bolds 'hello'
quill.formatText(0, 5, { // unbolds 'hello' and set its color to blue
'bold': false,
'color': 'rgb(0, 0, 255)'
});
quill.formatText(5, 1, 'align', 'right'); // right aligns the 'hello' line
getFormat
// Method
getFormat(range: Range = current): { [String]: any }
getFormat(index: Number, length: Number = 0): { [String]: any }
// Examples
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' }
removeFormat
"user"
, "api"
, or "silent"
. Calls where the source
is "user"
when the editor is disabled are ignored.
// Method
removeFormat(index: Number, length: Number, source: String = 'api'): Delta
// Examples
quill.setContents([
{ insert: 'Hello', { bold: true } },
{ insert: '\n', { align: 'center' } },
{ insert: { formula: 'x^2' } },
{ insert: '\n', { align: 'center' } },
{ insert: 'World', { italic: true }},
{ insert: '\n', { align: 'center' } }
]);
quill.removeFormat(3, 7);
// Editor contents are now
// [
// { insert: 'Hel', { bold: true } },
// { insert: 'lo\n\nWo' },
// { insert: 'rld', { italic: true }},
// { insert: '\n', { align: 'center' } }
// ]
Selection
getBounds
// Method
getBounds(index: Number, length: Number = 0): { left: Number, top: Number, height: Number, width: Number }
// Examples
quill.setText('Hello\nWorld\n');
quill.getBounds(7); // Returns { height: 15, width: 0, left: 27, top: 31 }
getSelection
null
may be returned if editor does not have focus.
// Method
getSelection(focus = false): { index: Number, length: Number }
// Examples
var range = quill.getSelection();
if (range) {
if (range.length == 0) {
console.log('User cursor is at index', range.index);
} else {
var text = quill.getText(range.index, range.length);
console.log('User has highlighted: ', text);
}
} else {
console.log('User cursor is not in editor');
}
setSelection
null
as the selection range will blur the editor. Source may be "user"
, "api"
, or "silent"
.
// Method
setSelection(index: Number, length: Number = 0, source: String = 'api')
setSelection(range: { index: Number, length: Number }, source: String = 'api')
// Examples
quill.setSelection(0, 5);
Editor
blur
// Method
blur()
// Examples
quill.blur();
enable
source
is "api"
or “silent”
.
// Method
enable(enabled: boolean = true)
// Examples
quill.enable();
quill.enable(false); // Disables user input
focus
// Method
focus()
// Examples
quill.focus();
hasFocus
// Method
hasFocus(): Boolean
// Examples
quill.hasFocus();
update
"user"
, "api"
, or "silent"
.
// Method
update(source: String = 'user')
// Examples
quill.update();
Extension
debug
'error'
, 'warn'
, 'log'
, or 'info'
. Passing true is equivalent to passing 'log'
. Passing false disables all messages.
// Method
Quill.debug(level: String | Boolean)
// Examples
Quill.debug('info');
import
// Method
Quill.import(path): any
// Examples
var Parchment = Quill.import('parchment');
var Delta = Quill.import('delta');
var Toolbar = Quill.import('modules/toolbar');
var Link = Quill.import('formats/link');
register
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.
// Method
Quill.register(format: Attributor | BlotDefinintion, supressWarning: Boolean = false)
Quill.register(path: String, def: any, supressWarning: Boolean = false)
Quill.register(defs: { [String]: any }, supressWarning: Boolean = false)
// Examples
Quill.register({
'formats/custom-format': CustomFormat,
'modules/custom-module-a': CustomModuleA,
'modules/custom-module-b': CustomModuleB,
});
Quill.register(CustomFormat);
addContainer
ql-
. Optionally include a refNode where container should be inserted before.
// Method
addContainer(className: String, refNode?: Node): Element
addContainer(domNode: Node, refNode?: Node): Element
// Examples
var container = quill.addContainer('ql-custom');
getModule
// Method
getModule(name: String): any
// Examples
var toolbar = quill.getModule('toolbar');
Events
text-change
Emitted when the contents of Quill have changed. Details of the change, representation of the editor contents before the change, along with the source of the change are provided. The source will be "user"
if it originates from the users. For example:
- User types into the editor
- User formats text using the toolbar
- User uses a hotkey to undo
- User uses OS spelling correction
Changes may occur through an API but as long as they originate from the user, the provided source should still be "user"
. For example, when a user clicks on the toolbar, technically the toolbar module calls a Quill API to effect the change. But source is still "user"
since the origin of the change was the user’s click.
APIs causing text to change may also be called with a "silent"
source, in which case text-change
will not be emitted. This is not recommended as it will likely break the undo stack and other functions that rely on a full record of text changes.
text-change
handler, the selection is not yet updated, and native browser behavior may place it in an inconsistent state. Use selection-change
or editor-change
for reliable selection updates.
// Callback signature
handler(delta: Delta, oldContents: Delta, source: String)
// Examples
quill.on('text-change', function(delta, oldDelta, source) {
if (source == 'api') {
console.log("An API call triggered this change.");
} else if (source == 'user') {
console.log("A user action triggered this change.");
}
});
selection-change
Emitted when a user or API causes the selection to change, with a range representing the selection boundaries. A null range indicates selection loss (usually caused by loss of focus from the editor). You can also use this event as a focus change event by just checking if the emitted range is null or not.
APIs causing the selection to change may also be called with a"silent"
source, in which case selection-change
will not be emitted. This is useful if selection-change
is a side effect. For example, typing causes the selection to change but would be very noisy to also emit a selection-change
event on every character.
// Callback signature
handler(range: { index: Number, length: Number }, oldRange: { index: Number, length: Number }, source: String)
// Examples
quill.on('selection-change', function(range, oldRange, source) {
if (range) {
if (range.length == 0) {
console.log('User cursor is on', range.index);
} else {
var text = quill.getText(range.index, range.length);
console.log('User has highlighted', text);
}
} else {
console.log('Cursor not in the editor');
}
});
editor-change
text-change
or selection-change
would be emitted, even when the source is "silent"
. The first parameter is the event name, either text-change
or selection-change
, followed by the arguments normally passed to those respective handlers.
// Callback signature
handler(name: String, ...args)
// Examples
quill.on('editor-change', function(eventName, ...args) {
if (eventName === 'text-change') {
// args[0] will be delta
} else if (eventName === 'selection-change') {
// args[0] will be old range
}
});
on
selection-change
for more details on the events themselves.
// Callback signature
on(name: String, handler: Function): Quill
// Examples
quill.on('text-change', function() {
console.log('Text change!');
});
once
text-change
or selection-change
for more details on the events themselves.
// Callback signature
once(name: String, handler: Function): Quill
// Examples
quill.once('text-change', function() {
console.log('First text change!');
});
off
// Callback signature
off(name: String, handler: Function): Quill
// Examples
function handler() {
console.log('Hello!');
}
quill.on('text-change', handler);
quill.off('text-change', handler);
Trumbowyg
Overview
Trumbowyg is a lightweight WYSIWYG editor optimized for HTML5 support. Options and design are entirely configurable to suit your needs. However, the default design is compatible with Retina display and optimized for a great and simple user experience. Editor can be extended with additional plugins, supports 30+ languages and custom packages. Trumbowyg is an MIT-licensed open source project and completely free to use.Usage
Installation is fairly simple - just load trumbowyg.min.js
after jquery.min.js
(minimum required version 1.8), make sure $enable-trumbowyg
variable in _config.scss
is set to true
and initialize plugin in JS:
If you don't already do it, load jQuery at bottom of <body>
or in <head>
and load Trumbowyg after it. In addition, load necessary plugins:
<!-- Include jQuery -->
<script src="assets/js/jquery/jquery.min.js"></script>
<!-- Include editor -->
<script src="assets/js/vendor/editors/trumbowyg/trumbowyg.min.js"></script>
<!-- Plugins -->
<script src="assets/js/vendor/editors/trumbowyg/plugins/base64/trumbowyg.base64.js"></script>
<script src="assets/js/vendor/editors/trumbowyg/plugins/cleanpaste/trumbowyg.cleanpaste.js"></script>
<script src="assets/js/vendor/editors/trumbowyg/plugins/colors/trumbowyg.colors.js"></script>
<script src="assets/js/vendor/editors/trumbowyg/plugins/insertaudio/trumbowyg.insertaudio.js"></script>
<script src="assets/js/vendor/editors/trumbowyg/plugins/noembed/trumbowyg.noembed.js"></script>
<script src="assets/js/vendor/editors/trumbowyg/plugins/preformatted/trumbowyg.preformatted.js"></script>
<script src="assets/js/vendor/editors/trumbowyg/plugins/template/trumbowyg.template.js"></script>
<script src="assets/js/vendor/editors/trumbowyg/plugins/upload/trumbowyg.upload.js"></script>
<script src="assets/js/vendor/editors/trumbowyg/plugins/pasteimage/trumbowyg.pasteimage.js"></script>
This the minimal code to transform a simple div into the amazing WYSIWYG editor which is Trumbowyg. Or if you want to set options to Trumbowyg, add an object which contains your options as parameters:
// Initialize default editor
$('#trumbowyg-demo').trumbowyg();
// Initialize with options
$('#trumbowyg-demo').trumbowyg({
btns: ['strong', 'em', '|', 'insertImage'],
autogrow: true
});
Options
Following is a list of all configuration parameters with their corresponding default values:
You can change prefix of all class added on elements of Trumbowyg using this option:
// Initialize
$('textarea').trumbowyg({
prefix: 'custom-prefix'
});
Your users don't speak english? No problem, Trumbowyg has a language parameter. You have to load the appropriate lang file. Search in /dist/langs
folder to see if a language file already exists, if not create it and share it :). Don't forget include the lang file in your pages:
<!-- Include lang file -->
<script type="text/javascript" src="js/dist/langs/fr.min.js"></script>
Make sure to include lang file after Trumbowyg and before instantiating the editor!
Usage of language parameter (English is a fallback lang):
// Initialize
$('textarea').trumbowyg({
lang: 'fr'
});
It's probably the most interesting option, it allows you to choose the buttons that appears in the button pane. This option is an array containing string values representing the buttons or vertical separators (using the pipe character). To create your own custom button pane, define an array and pass it to the btns
option:
// Custom button set
$('.simple-editor').trumbowyg({
btns: [['bold', 'italic'], ['link']]
});
// Default button set
$('.simple-editor').trumbowyg({
btns: [
['viewHTML'],
['undo', 'redo'], // Only supported in Blink browsers
['formatting'],
['strong', 'em', 'del'],
['superscript', 'subscript'],
['link'],
['insertImage'],
['justifyLeft', 'justifyCenter', 'justifyRight', 'justifyFull'],
['unorderedList', 'orderedList'],
['horizontalRule'],
['removeformat'],
['fullscreen']
]
});
You can hide button texts showed when you put svgPath
to false
// Globally
$.trumbowyg.hideButtonTexts = true
// Or locally
$('.trumbowyg').trumbowyg({
hideButtonTexts: true
});
Generates a better, more semantic oriented HTML (i.e. <em>
instead of <i>
, <strong>
instead of <b>
, etc.). It's just a boolean. This option deactivates the underline button by default because they do not convey any real semantic. If you want to reactivate them, you have to do it explicitly
:
// Initialize
$('.trumbowyg').trumbowyg({
semantic: false
});
If you don't want the page style to impact on the look of the text in the editor, you will need to apply a reset-css on the editor. You can activate this with the resetCss
option:
// Initialize
$('.trumbowyg').trumbowyg({
resetCss: true
});
If you don't want styles pasted from clipboard (from Word or other webpage for example), pass the removeformatPasted
option to true
. In order to use this option, you need to define a font size in your CSS or use a reset like normalize.
// Initialize
$('.trumbowyg').trumbowyg({
removeformatPasted: true
});
The text editing zone can extend itself when writing a long text. To activate this feature, use the autogrow option::
// Initialize
$('.trumbowyg').trumbowyg({
autogrow: true
});
The text editing zone can extend itself when editor get focus and reduce on blur. To activate this feature, use the following option:
// Initialize
$('.trumbowyg').trumbowyg({
autogrowOnEnter: true
});
Add a field in image insert/edit modal which allow users to set the image width. To activate this feature, use the following option:
// Initialize
$('.trumbowyg').trumbowyg({
imageWidthModalEdit: true
});
An option to auto-prefix URLs with a protocol. When this option is set to true
, URLs missing a protocol will be prefixed with https://
. Alternatively, a string can be provided for a custom prefix. For example, a value of true would convert example.com to https://example.com, while a value of ftp converts to ftp://example.com.
// Initialize
$('.trumbowyg').trumbowyg({
urlProtocol: true
});
Reduce the link overlay to use only url
and text
fields, omitting title
and target
.
// Initialize
$('.trumbowyg').trumbowyg({
minimalLinks: true
});
Modal box API
When you want create your custom extension for Trumbowyg, you can open and close a modal box with custom inner HTML code, listen events and more:
For that use the .trumbowyg()
method and give parameters 'openModal'
or 'closeModal'
like that:
// Open modal box
var $modal = $('#editor').trumbowyg('openModal', {
title: 'A title for modal box',
content: '<p>Content in HTML which you want include in created modal box</p>'
});
// Close current modal box
$('#editor').trumbowyg('closeModal');
An openModal
call returns a jQuery object which contains the modal box. You need this object if you want to use listen events (see below)
- tbwsubmit: trigged when form is submit
- tbwreset: trigged when user cancel operation
// Open modal
var $modal = $('#editor').trumbowyg('openModal', {
title: 'A title for modal box',
content: '<p>Content in HTML which you want include in created modal box</p>'
});
// Listen clicks on modal box buttons
$modal.on('tbwconfirm', function(e){
// Save datas
$("#editor").trumbowyg('closeModal');
});
$modal.on('tbwcancel', function(e){
$('#editor').trumbowyg('closeModal');
});
If you want only add inputs in the modal box, this function is more simple. Indeed, you do not manage confirm and close buttons, and get all input value on confirm.
// Config
var img = $('img#an-img');
$("#editor").trumbowyg('openModalInsert', {
title: 'A title for modal box',
fields: {
url: {
value: img.attr('src')
},
alt: {
label: 'Alt',
name: 'alt',
value: img.attr('alt'),
type: 'text'.
attributes: {}
},
example: {
// Missing label is replaced by the key of this object (here 'example')
// Missing name is the key
// When value is missing, value = ''
// When type is missing, 'text' is assumed. You can use all the input field types,
// plus checkbox and radio (select and textarea are not supported)
// When attributes is missing, {} is used. Attributes are added as attributes to
// the input element.
// For radio and checkbox fields, you will need to use attributes if you want it
// to be checked by default.
}
},
callback: function(values){
img.attr('src', values['url']);
img.attr('alt', values['alt']);
return true; // Return true if you have finished with this modal box
// If you do not return anything, you must manage the closing of the modal box yourself
}
});
// You can also listen for modal confirm/cancel events to do some custom things
// Note: the openModalInsert callback is called on tbwconfirm
$modal.on('tbwconfirm', function(e){
// Do what you want
});
$modal.on('tbwcancel', function(e){
trumbowyg.closeModal();
});
Range
Managing correctly text range, is not so trivial. Trumbowyg has a system to save and restore selection range which does not involves typical getter/setter.
// Save current range
$('#editor').trumbowyg('saveRange');
// Restore last saved range
$('#editor').trumbowyg('restoreRange');
// Range contains a JavaScript range
var range = $('#editor').trumbowyg('getRange');
// Get text
var text = $('#editor').trumbowyg('getRangeText');
Manage content
You can set and get current HTML content of the editor with a getter/setter:
// Get HTML content
$('#editor').trumbowyg('html');
// Set HTML content
$('#editor').trumbowyg('html', "<p>Your content here</p>");
Empty
You can empty the content of the editor.
// Clear editor
$('#editor').trumbowyg('empty');
Enable/disable edition
As you can disable editor by using disabled
option, you can also switch between enabled and disabled states by using API.
// States
$('#editor').trumbowyg('disable');
$('#editor').trumbowyg('enable');
Toggle between HTML & WYSIWYG modes
You can switch between HTML view and WYSIWYG view via toggle method.
// Toggle views
$('#editor').trumbowyg('toggle');
Destroy editor
When you wish, you can restore the previous state of the element was used to create the editor.
// Destroy editor
$('#editor').trumbowyg('destroy');
Events
- Focus on editor:
tbwfocus
- Blur on editor:
tbwblur
- Editor is initialized:
tbwinit
- Change in editor:
tbwchange
- Resize the editor on autogrow:
tbwresize
- Paste something in the editor:
tbwpaste
- Switch to fullscreen mode:
tbwopenfullscreen
- Leave editor's fullscreen mode:
tbwclosefullscreen
- Close the editor:
tbwclose
// Events
$('#editor')
.trumbowyg() // Build Trumbowyg on the #editor element
.on('tbwfocus', function(){ console.log('Focus!'); }); // Listen for `tbwfocus` event
.on('tbwblur', function(){ console.log('Blur!'); }); // Listen for `tbwblur` event