CKEditor live preview
by TicoRicoRay
HTML
<script src="//cdn.ckeditor.com/4.4.0/standard/ckeditor.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="iteration">
<option value="0" selected>1</option>
<option value="1">2</option>
<option value="2">3</option>
</select>
<div id="container">
<textarea id="editor">
<p>Hello world!.</p>
<p>Here [is some text|are some words|is a bit of hyperlingo].</p>
<p>What do you think?
</p>
</textarea>
<div id="preview"></div>
</div>
CSS
body{font-family:Arial;}
#container {display:flex;}
#preview { outline: 1px solid #ccc; padding: 4px; margin: 0 0 0 20px }
JavaScript
var preview = CKEDITOR.document.getById( 'preview' );
function syncPreview() {
var s = editor.getData();
var i = $("#iteration option:selected").val();
preview.setHtml( decode(s,i ));
}
function decode(text, iteration) {
var t = "";
var separators = ['\\[', '\\]'];
var a = text.split(new RegExp(separators.join('|'), 'g'));
var l = a.length;
for (var i = 0; i < l; i++) {
t = t + synonym_Pick(a[i], iteration);
}
return t;
}
//chooses a synonym from delimited text
function synonym_Pick(text, iteration) {
var w = "";
var a = text.split("|");
var l = a.length;
if (l === 1) {
return text;
} else {
w = a[iteration%l];
return w;
}
}
$("#iteration").on("change", syncPreview)
var editor = CKEDITOR.replace( 'editor', {
on: {
// Synchronize the preview on user action that changes the content.
change: syncPreview,
// Synchronize the preview when the new data is set.
contentDom: syncPreview
}
} );