| [ Web Proxy ] |
| Viewing: https://tryenlight.github.io/code-editor.html | [Back] [Original] |
In this project, well be building a live code editor similar to Codepen or JsFiddle.
Lets get started by creating our usual three files:
To get started with our markup, well be needing three textarea tags which will correspond with the id of the language well 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>
Before we head on to making our app, lets 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!
Now, heres where we actually make our app functional. We can do so with just one function. Heres what well 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!
Enlight 2017 by shamdasani.org
Enlight 2016-2018 by shamdasani.org
| Web Proxy Viewer | New URL | Original Page |