Search code examples
javascriptvisual-studio-codeadobe-bracketsplunkerlive-preview

How to live preview a set of files?


I want to build a simple online editor like plunker. Does anyone know how to accomplish the live preview, once several files (.html, .css, .js, .json) have been uploaded?

Taking JSBin as example, there are only 1 html text, 1 css text and 1 js text, so it is simple: we just need to construct one complete html file from these texts and use Document.write().

However, how do editors such as plunker, brackets, vscode do live preview? Do they also construct one complete file by themselves or they use some third-party tools?


Solution

  • Live previews are pretty easy. Just replace the HTML of an area on the page with the HTML the user provided. In practice, you probably want to do this in a sandboxed iframe for security purposes.

    The snippet below shows how this can be done, all in JavaScript. Try running the snippet and typing in the box.

    function doLivePreview() {
      $("#output").html($("#source").val());
    }
    
    $(function() {
      doLivePreview();
      $("#source").on("input", doLivePreview);
    });
    #source {
      float: left;
    }
    
    #output {
      float: left;
      border: 1px solid #AAA;
      margin-left: 5px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <textarea id="source" cols="50" rows="8">
    Type to see a live preview
    <br/>
    <a href="https://www.google.com">Google<a>
    </textarea>
    <div id="output">
    </div>