How to Create a Text Editor Live Preview

Getting Started

First, we need Bootstrap, jQuery and the WYSIHTML5 plugin that will provide our WYSIHTML5 editor which are included in the downloadable of this tutorial.

Creating the Page

Finally, we create our page with the text editor, iframe and our scripts.
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.         <meta charset="utf-8">
  5.         <title>How to Create a Text Editor Live Preview</title>
  6.         <link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css">
  7.                 <link rel="stylesheet" type="text/css" href="bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css">
  8. </head>
  9. <body>
  10. <div class="container">
  11.         <h1 class="page-header text-center">Create a Text Editor Live Preview</h1>
  12.         <div class="row">
  13.                 <div class="col-sm-6">
  14.                         <textarea id="content" name="content" class="form-control" rows="10">Try to edit Me!</textarea>
  15.                         <br>
  16.                         <button type="button" id="run" class="btn btn-primary">Preview</button>
  17.                 </div>
  18.                 <div class="col-sm-6">
  19.                         <iframe name="landingPage" id="landingPage" class="col-lg-12 col-md-12 col-sm-12" height="400px"></iframe>
  20.                 </div>
  21.         </div>
  22. </div>
  23.  
  24. <script src="jquery/jquery.min.js"></script>
  25. <script src="bootstrap/js/bootstrap.min.js"></script>
  26. <script src="bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js"></script>
  27. <script type="text/javascript">
  28. $(function () {
  29.     //Add text editor
  30.     $("#content").wysihtml5();
  31.  
  32.     var content = $('#content').val();
  33.     runCode(content);
  34.  
  35.     $('#run').click(function(){
  36.         content = $('#content').val();
  37.         runCode(content);
  38.     });
  39. })
  40.  
  41. function runCode(content){     
  42.         var iframe = document.getElementById('landingPage');
  43.         iframe = (iframe.contentWindow) ? iframe.contentWindow : (iframe.contentDocument.document) ? iframe.contentDocument.document : iframe.contentDocument;
  44.         iframe.document.open();
  45.         iframe.document.write(content);
  46.         iframe.document.close();
  47.         return false;
  48. }
  49. </script>
  50. </body>
  51. </html>
That ends this tutorial. Happy Coding :)

Comments

Add new comment