Build a Live HTML/CSS/JS Editor



Tweet

Getting Started

In this project, we’ll be building a live code editor similar to Codepen or JsFiddle.

Let’s get started by creating our usual three files:

To get started with our markup, we’ll be needing three textarea tags which will correspond with the id of the language we’ll be compiling. To actually show the compiled code, we will also need an iframe which will allow us to insert an html document into an existing html page. Make sure to set ids for each tag so we can communicate with these elements in JavaScript.

<html>
    <head>
      <title>Code Editor</title>
      <meta name="viewport" content="width=device-width, initial-scale=1">

      <link rel="stylesheet" href="style.css">
    </head>

    <body>

      <textarea id="html" placeholder="HTML"></textarea>
      <textarea id="css" placeholder="CSS"></textarea>
      <textarea id="js" placeholder="JavaScript"></textarea>
      <iframe id="code"></iframe>

      <script type="text/javascript" src="app.js"></script>

    </body>
  </html>

Making it look decent

Before we head on to making our app, let’s style it up a bit. We should align the elements to the center, make the textarea elements go side by side, and put the iframe right below them.

  body {
    text-align: center;
  }

  textarea {
    width: 32%;
    float: top;
    min-height: 250px;
    overflow: scroll;
    margin: auto;
    display: inline-block;
    background: #F4F4F9;
    outline: none;
    font-family: Courier, sans-serif;
    font-size: 14px;
  }

  iframe {
    bottom: 0;
    position: relative;
    width: 100%;
    height: 35em;
  }


As always, feel free to customize this to your liking!

Our compile() function

Now, here’s where we actually make our app functional. We can do so with just one function. Here’s what we’ll need to write in it:

  function compile() {

    var html = document.getElementById("html");
    var css = document.getElementById("css");
    var js = document.getElementById("js");
    var code = document.getElementById("code").contentWindow.document;

     document.body.onkeyup = function(){
      code.open();
      code.writeln(html.value+"<style>"+css.value+"</style>"+"<script>" + js.value + "</script>");
      code.close();
        };
      };

  compile();

That's it! Pretty simple right? To take this a step further, try and make the textareas responsive with media queries. If you liked this tutorial, try building a Web Paint app!