Today we're gonna prepare a live preview of the contents edited with CKEditor.
A live preview with a WYSIWYG editor is not so important compared to other text-based editors, but anyways the behavior inside the editor might not match exactly the final output, so in those cases we can provide this option for those that want it.
Ingredients:
1 Instance of CKEditor
1 Preview container (for example a Div)
1 Copy of the onChange plugin
In case that you want to use this method with more than one instances, then you'll need as many preview containers as CKEditor instances you want to use.
Method:
1. Create the CKEditor instance in your page using any method that you like, and add the OnChange plugin to the list of extra plugins:
For example:
<textarea name='contents' id='contents'>This is an editor</textarea>
<script type='text/javascript'>
var config = { extraPlugins: 'onchange'};
CKEDITOR.replace('contents', config);
</script>
2. Now add add a little extra javascript to listen for changes in the editor instance and mirror those changes in the preview div, (based on this StackOverflow question)
CKEDITOR.on('instanceCreated', function (e) {
e.editor.on('change', function (ev) {
document.getElementById( ev.editor.name + '_preview').innerHTML = ev.editor.getData();
});
});
That code will take care of any CKEditor instance and automatically copy its contents into the container with an id like the editor instance with an ending "_preview".
3. The only missing part is to initialize the preview before the user starts typing:
document.getElementById( e.editor.name + '_preview').innerHTML = e.editor.getData();
All the code together
<textarea id="contents" name="contents">This is an editor</textarea></p>
<div id="contents_preview"></div>
<script type='text/javascript'>
CKEDITOR.on('instanceCreated', function (e) {
document.getElementById( e.editor.name + '_preview').innerHTML = e.editor.getData();
e.editor.on('change', function (ev) {
document.getElementById( ev.editor.name + '_preview').innerHTML = ev.editor.getData();
});
});
var config = { extraPlugins: 'onchange'};
CKEDITOR.replace('contents', config);
</script>
This code in action: