Skip to content

Instantly share code, notes, and snippets.

@ppbntl19
Last active July 5, 2018 21:53
Show Gist options
  • Save ppbntl19/455f68af728382e001070d9cced0c70e to your computer and use it in GitHub Desktop.
Save ppbntl19/455f68af728382e001070d9cced0c70e to your computer and use it in GitHub Desktop.
Bootstrap-wysiwyg minimal usage ( supoort added without jQuery HotKeys and Font-Awesome.css )

Bootstrap-wysiwyg minimal usage ( supoort added without jQuery HotKeys and Font-Awesome.css )

bootstrap-wysiwyg

GitHub release GitHub license

A tiny Bootstrap and jQuery based WYSIWYG rich text editor based on the browser function execCommand.

This project was originally built for MindMup and has now been adapted and modified to suit a wide range of projects.

Development is active, and ongoing.

Features

  • Automatically binds standard hotkeys for common operations on Mac and Windows
  • Allows a custom built toolbar with no magic markup generators enabling the web site to use all the goodness of Bootstrap
  • Does not force any styling - it's all up to you
  • Uses standard browser features, no magic non-standard code, toolbar and keyboard configurable to execute any supported browser command
  • Does not create a separate frame, backup text areas etc - instead keeps it simple and runs everything inline in a DIV
  • (Optionally) cleans up trailing whitespace and empty divs and spans
  • Requires a modern browser (See SUPPORTED)
  • Supports mobile devices (See SUPPORTED)
  • Supports multiple instances
  • HTML Sanitization
  • Drag and drop files to insert images
  • Supports image upload
  • Supports image capture on mobile devices
  • Events

Basic Usage

$('#editor').wysiwyg();

Don't forget to style your editor div:

#editor {overflow:scroll; max-height:300px}

If you want to use this for a mobile web site, make sure to read about how to style it to optimise mobile screen usage and experience (please note that this demo page isn't optimised for mobile access).

Optionally, also create a toolbar (see the source of this page for an example):

<div class="btn-toolbar" data-role="editor-toolbar"
        data-target="#editor">
  ...
</div> 

In the toolbar, execute simple commands by adding a data-edit attribute to a link.

<a data-edit="bold">...</a>

execute more complex commands by adding an argument after a blank or providing an input with a data-edit command (the input value is used as an argument). In case of file inputs, the file contents are read in using the FileReader API and used as the command value.

<a data-edit="fontName Arial">...</a>
...
<input type="text" data-edit="createLink"/>
...
<input type="file" data-edit="insertImage" />

Use standard jQuery methods to access and set content and focus. You can also ask for cleaned up HTML content:

$('#editor').cleanHtml()

Customising

You can assign commands to hotkeys and toolbar links. For a toolbar link, just put the execCommand command name into a data-edit attribute. For more info on execCommand, see the QuirksMode and Mozilla Developer documentation.

<div class="btn-toolbar" data-role="editor-toolbar" data-target="#editor">
  <a class="btn btn-large" data-edit="bold"><i class="icon-bold"></i></a>
</div>

To pass arguments to a command, separate a command with a space.

  <a data-edit="fontName Arial">...</a>

You can also use input type='text' with a data-edit attribute. When the value is changed, the command from the data-edit attribute will be applied using the input value as the command argument

<input type="text" data-edit="createLink">

If the input type is file, when a file is selected the contents will be read in using the FileReader API and the data URL will be used as the argument

<input type="file" data-edit="insertImage">

To change hotkeys, specify the map of hotkeys to commands in the hotKeys option. For example:

$('#editor').wysiwyg({
  hotKeys: {
    'ctrl+b meta+b': 'bold',
    'ctrl+i meta+i': 'italic',
    'ctrl+u meta+u': 'underline',
    'ctrl+z meta+z': 'undo',
    'ctrl+y meta+y meta+shift+z': 'redo'
  }
});

Events

Change

Fired whenever anything changes. See this example events.html

$('#editor').wysiwyg().on('change', function(){
	alert('something has been changed on the editor');
});

Styling for mobile devices

This editor should work pretty well with mobile devices, but you'll need to consider the following things when styling it:

  • keyboards on mobile devices take a huge part of the screen
  • having to scroll the screen to touch the toolbar can cause the editing component to lose focus, and the mobile device keyboard might go away
  • mobile devices tend to move the screen viewport around to ensure that the focused element is shown, so it's best that the edit box is glued to the top

For the content attachment editor on MindMup, we apply the following rules to mobile device styling:

  • edit box is glued to the top, so the focus doesn't jump around
  • toolbar is below the edit box
  • on portrait screens, edit box size is 50% of the screen
  • on landscape screens, edit box size is 30% of the screen
  • as the screen gets smaller, non-critical toolbar buttons get hidden into a "other" menu

Dependencies

Thanks to

@gojko @mindmup @jordanh @beatnbite @brutuscat @VictorBjelkholm @mrmrs @tilleryd @pnevels

History

The original version of this code (below) appeared to be no longer maintained. There were a number of outstanding changes which needed to be merged in and a few which included performance and feature improvements. These have now been included in this master branch.

I'll keep an eye out for future changes/improvements and pull them in as required.

  • Steve

Original Licence

The original version of this tool can be found here: bootstrap-wysiwyg

The MIT License

Copyright (c) 2013 Damjan Vujnovic, David de Florinier, Gojko Adzic

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

/* @fileoverview
* Provides full Bootstrap based, multi-instance WYSIWYG editor.
*
* "Name" = 'bootstrap-wysiwyg'
* "Author" = 'Various, see LICENSE'
* "Version" = '1.0.4'
* "About" = 'A tiny Bootstrap and jQuery based WYSIWYG rich text editor based on the browser function execCommand.'
*/
(function ($) {
'use strict';
var readFileIntoDataUrl = function (fileInfo) {
var loader = $.Deferred(),
fReader = new FileReader();
fReader.onload = function (e) {
loader.resolve(e.target.result);
};
fReader.onerror = loader.reject;
fReader.onprogress = loader.notify;
fReader.readAsDataURL(fileInfo);
return loader.promise();
};
$.fn.cleanHtml = function (o) {
if ( $(this).data("wysiwyg-html-mode") === true ) {
$(this).html($(this).text());
$(this).attr('contenteditable',true);
$(this).data('wysiwyg-html-mode',false);
}
// Strip the images with src="data:image/.." out;
if ( o === true && $(this).parent().is("form") ) {
var gGal = $(this).html;
if ( $(gGal).has( "img" ).length ) {
var gImages = $( "img", $(gGal));
var gResults = [];
var gEditor = $(this).parent();
$.each(gImages, function(i,v) {
if ( $(v).attr('src').match(/^data:image\/.*$/) ) {
gResults.push(gImages[i]);
$(gEditor).prepend("<input value='"+$(v).attr('src')+"' type='hidden' name='postedimage/"+i+"' />");
$(v).attr('src', 'postedimage/'+i);
}});
}
}
var html = $(this).html();
return html && html.replace(/(<br>|\s|<div><br><\/div>|&nbsp;)*$/, '');
};
$.fn.wysiwyg = function (userOptions) {
var editor = this,
selectedRange,
options,
toolbarBtnSelector,
updateToolbar = function () {
if (options.activeToolbarClass) {
$(options.toolbarSelector).find(toolbarBtnSelector).each(function () {
var commandArr = $(this).data(options.commandRole).split(' '),
command = commandArr[0];
// If the command has an argument and its value matches this button. == used for string/number comparison
if (commandArr.length > 1 && document.queryCommandEnabled(command) && document.queryCommandValue(command) === commandArr[1]) {
$(this).addClass(options.activeToolbarClass);
// Else if the command has no arguments and it is active
} else if (commandArr.length === 1 && document.queryCommandEnabled(command) && document.queryCommandState(command)) {
$(this).addClass(options.activeToolbarClass);
// Else the command is not active
} else {
$(this).removeClass(options.activeToolbarClass);
}
});
}
},
execCommand = function (commandWithArgs, valueArg) {
var commandArr = commandWithArgs.split(' '),
command = commandArr.shift(),
args = commandArr.join(' ') + (valueArg || '');
var parts = commandWithArgs.split('-');
if ( parts.length === 1 ) {
document.execCommand(command, false, args);
}
else if ( parts[0] === 'format' && parts.length === 2 ) {
document.execCommand('formatBlock', false, parts[1] );
}
editor.trigger('change');
updateToolbar();
},
bindHotkeys = function (hotKeys) {
$.each(hotKeys, function (hotkey, command) {
editor.keydown(hotkey, function (e) {
if (editor.attr('contenteditable') && editor.is(':visible')) {
e.preventDefault();
e.stopPropagation();
execCommand(command);
}
}).keyup(hotkey, function (e) {
if (editor.attr('contenteditable') && editor.is(':visible')) {
e.preventDefault();
e.stopPropagation();
}
});
});
editor.keyup(function(){ editor.trigger('change'); });
},
getCurrentRange = function () {
var sel, range;
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
}
} else if (document.selection) {
range = document.selection.createRange();
} return range;
},
saveSelection = function () {
selectedRange = getCurrentRange();
},
restoreSelection = function () {
var selection;
if (window.getSelection || document.createRange) {
selection = window.getSelection();
if (selectedRange) {
try {
selection.removeAllRanges();
} catch (ex) {
document.body.createTextRange().select();
document.selection.empty();
}
selection.addRange(selectedRange);
}
}
else if (document.selection && selectedRange) {
selectedRange.select();
}
},
// Adding Toggle HTML based on the work by @jd0000, but cleaned up a little to work in this context.
toggleHtmlEdit = function() {
if ( $(editor).data("wysiwyg-html-mode") !== true ) {
var oContent = $(editor).html();
var editorPre = $( "<pre />" );
$(editorPre).append( document.createTextNode( oContent ) );
$(editorPre).attr('contenteditable',true);
$(editor).html(' ');
$(editor).append($(editorPre));
$(editor).attr('contenteditable', false);
$(editor).data("wysiwyg-html-mode", true);
$(editorPre).focus();
}
else {
$(editor).html($(editor).text());
$(editor).attr('contenteditable',true);
$(editor).data('wysiwyg-html-mode',false);
$(editor).focus();
}
},
insertFiles = function (files) {
editor.focus();
$.each(files, function (idx, fileInfo) {
if (/^image\//.test(fileInfo.type)) {
$.when(readFileIntoDataUrl(fileInfo)).done(function (dataUrl) {
execCommand('insertimage', dataUrl);
editor.trigger('image-inserted');
}).fail(function (e) {
options.fileUploadError("file-reader", e);
});
} else {
options.fileUploadError("unsupported-file-type", fileInfo.type);
}
});
},
markSelection = function (input, color) {
restoreSelection();
if (document.queryCommandSupported('hiliteColor')) {
document.execCommand('hiliteColor', false, color || 'transparent');
}
saveSelection();
input.data(options.selectionMarker, color);
},
bindToolbar = function (toolbar, options) {
toolbar.find(toolbarBtnSelector).click(function () {
restoreSelection();
editor.focus();
if ($(this).data(options.commandRole) === 'html') {
toggleHtmlEdit();
}
else {
execCommand($(this).data(options.commandRole));
}
saveSelection();
});
toolbar.find('[data-toggle=dropdown]').click(restoreSelection);
toolbar.find('input[type=text][data-' + options.commandRole + ']').on('webkitspeechchange change', function () {
var newValue = this.value; /* ugly but prevents fake double-calls due to selection restoration */
this.value = '';
restoreSelection();
if (newValue) {
editor.focus();
execCommand($(this).data(options.commandRole), newValue);
}
saveSelection();
}).on('focus', function () {
var input = $(this);
if (!input.data(options.selectionMarker)) {
markSelection(input, options.selectionColor);
input.focus();
}
}).on('blur', function () {
var input = $(this);
if (input.data(options.selectionMarker)) {
markSelection(input, false);
}
});
toolbar.find('input[type=file][data-' + options.commandRole + ']').change(function () {
restoreSelection();
if (this.type === 'file' && this.files && this.files.length > 0) {
insertFiles(this.files);
}
saveSelection();
this.value = '';
});
},
initFileDrops = function () {
editor.on('dragenter dragover', false)
.on('drop', function (e) {
var dataTransfer = e.originalEvent.dataTransfer;
e.stopPropagation();
e.preventDefault();
if (dataTransfer && dataTransfer.files && dataTransfer.files.length > 0) {
insertFiles(dataTransfer.files);
}
});
};
options = $.extend(true, {}, $.fn.wysiwyg.defaults, userOptions);
toolbarBtnSelector = 'a[data-' + options.commandRole + '],button[data-' + options.commandRole + '],input[type=button][data-' + options.commandRole + ']';
//bindHotkeys(options.hotKeys);
// Support placeholder attribute on the DIV
var placeholder = $(this).attr('placeholder');
if (placeholder !== '') {
// Set iniitial state without trashing existing text.
if ( placeholder !== '' && $(this).text() === '' ) {
$(this).addClass('placeholderText');
$(this).html(placeholder);
}
$(this).bind('focus',function() {
if (placeholder !== '' && $(this).text() === placeholder ) {
$(this).removeClass('placeholderText');
$(this).html('');
}
});
$(this).bind('blur',function() {
if (placeholder !== '' && $(this).text() === '' ) {
$(this).addClass('placeholderText');
$(this).html(placeholder);
}
});
}
if (options.dragAndDropImages) {
initFileDrops();
}
bindToolbar($(options.toolbarSelector), options);
editor.attr('contenteditable', true)
.on('mouseup keyup mouseout', function () {
saveSelection();
updateToolbar();
});
$(window).bind('touchend', function (e) {
var isInside = (editor.is(e.target) || editor.has(e.target).length > 0),
currentRange = getCurrentRange(),
clear = currentRange && (currentRange.startContainer === currentRange.endContainer && currentRange.startOffset === currentRange.endOffset);
if (!clear || isInside) {
saveSelection();
updateToolbar();
}
});
return this;
};
$.fn.wysiwyg.defaults = {
hotKeys: {
'Ctrl+b meta+b': 'bold',
'Ctrl+i meta+i': 'italic',
'Ctrl+u meta+u': 'underline',
'Ctrl+z': 'undo',
'Ctrl+y meta+y meta+shift+z': 'redo',
'Ctrl+l meta+l': 'justifyleft',
'Ctrl+r meta+r': 'justifyright',
'Ctrl+e meta+e': 'justifycenter',
'Ctrl+j meta+j': 'justifyfull',
'Shift+tab': 'outdent',
'tab': 'indent'
},
toolbarSelector: '[data-role=editor-toolbar]',
commandRole: 'edit',
activeToolbarClass: 'btn-info',
selectionMarker: 'edit-focus-marker',
selectionColor: 'darkgrey',
dragAndDropImages: true,
keypressTimeout: 200,
fileUploadError: function (reason, detail) { console.log("File upload error", reason, detail); }
};
}(window.jQuery));
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Tiny, opensource, Bootstrap WYSIWYG rich text editor from MindMup</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="keywords" content="opensource rich wysiwyg text editor jquery bootstrap execCommand html5" />
<meta name="description" content="This tiny jQuery Bootstrap WYSIWYG plugin turns any DIV into a HTML5 rich text editor" />
<link rel="apple-touch-icon" href="//mindmup.s3.amazonaws.com/lib/img/apple-touch-icon.png" />
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script src="/bootstrap-wysiwyg.js"></script>
</head>
<body>
<div class="container">
<hr/>
<div class="col-xs-12">
<div class="row">
<div class="col-sm-12">
<div class="btn-toolbar" data-role="editor-toolbar" data-target="#editor" id="rich_text_editor_toolbar" style="padding: 10px 0px 10px 0px;">
<div class="btn-group">
<a class="btn btn-default dropdown-toggle" data-toggle="dropdown"
title="Font Size"><span class="glyphicon glyphicon-text-height"></span>&nbsp;<b
class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><a data-edit="fontSize 5"><font size="5">Huge</font></a></li>
<li><a data-edit="fontSize 3"><font size="3">Normal</font></a></li>
<li><a data-edit="fontSize 1"><font size="1">Small</font></a></li>
</ul>
</div>
<div class="btn-group">
<a class="btn btn-default" data-edit="bold" title="Bold (Ctrl/Cmd+B)"> <span class="glyphicon glyphicon-bold" aria-hidden="true"></span></a>
<a class="btn btn-default" data-edit="italic" title="Italic (Ctrl/Cmd+I)"><span class="glyphicon glyphicon-italic" aria-hidden="true"></span></i></a>
<a class="btn btn-default" data-edit="underline" title="Underline (Ctrl/Cmd+U)"> <span class="glyphicon glyphicon-magnet" aria-hidden="true"></span></a>
</div>
<div class="btn-group">
<a class="btn btn-default" data-edit="insertunorderedlist" title="Bullet list"> <span class="glyphicon glyphicon glyphicon-list" aria-hidden="true"></span></a>
<a class="btn btn-default" data-edit="insertorderedlist" title="Number list"> <span class="glyphicon glyphicon glyphicon-list" aria-hidden="true"></span></a>
<a class="btn btn-default" data-edit="outdent" title="Reduce indent (Shift+Tab)"> <span class="glyphicon glyphicon-indent-right" aria-hidden="true"></span></a>
<a class="btn btn-default" data-edit="indent" title="Indent (Tab)"> <span class="glyphicon glyphicon-indent-left" aria-hidden="true"></span></a>
</div>
<div class="btn-group">
<a class="btn btn-default" data-edit="justifyleft" title="Align Left (Ctrl/Cmd+L)"> <span class="glyphicon glyphicon-align-left" aria-hidden="true"></span></a>
<a class="btn btn-default" data-edit="justifycenter" title="Center (Ctrl/Cmd+E)"> <span class="glyphicon glyphicon-align-center" aria-hidden="true"></span></a>
<a class="btn btn-default" data-edit="justifyright" title="Align Right (Ctrl/Cmd+R)"> <span class="glyphicon glyphicon-align-right" aria-hidden="true"></span></a>
<a class="btn btn-default" data-edit="justifyfull" title="Justify (Ctrl/Cmd+J)"> <span class="glyphicon glyphicon-align-justify" aria-hidden="true"></span></a>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div id="rich_text_editor" class="form-control" data-placeholder="Go ahead&hellip;" style="height:250px;overflow: scroll;">
</div>
</div>
</div>
</div>
<script>
$(function()
{
$('#rich_text_editor').wysiwyg({} );
window.prettyPrint && prettyPrint();
});
</script>
</html>
@icandothat2
Copy link

This was annoyingly clever "'webkitspeechchange change"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment