This tutorial will help for all publisher who wants to give option to edit their code to the user to see the live try it edit the HTML CSS JavaScript code for demo.
This Tryit editor work like w3schools, tutorialspoint etc. User can change the look and feel editing the CSS
Let’s start the tutorials. Start with adding the code Mirror and JQuery library to the HTML page.
Add CodeMirror and JQuery
<script src="js/1.12.4/jquery.min.js"></script>
<script src="js/1.12.4/jquery-ui.js"></script>
<link rel=stylesheet href=lib/codemirror.css>
<script src=lib/codemirror.js></script>
<script src=lib/xml.js></script>
<script src=lib/javascript.js></script>
<script src=lib/css.js></script>
<script src=lib/closetag.js></script>
<script src=js/custom.js></script>
Add below style to set auto height to Editor
Below code will make the editor to resize automatically
<style type="text/css">
.CodeMirror {
height: auto;
}
</style>
Add HTML textarea
Below text area has the default html code in editor.
<textarea id=editor name=editor>
<!doctype html>
<html>
<head>
<meta charset=utf-8>
<title>HTML5 canvas demo</title>
<style>p {font-family: monospace;}</style>
</head>
<body>
<p>Canvas pane goes here:</p>
<canvas id=pane width=300 height=200></canvas>
<script>
var canvas = document.getElementById('pane');
var context = canvas.getContext('2d');
context.fillStyle = 'rgb(250,0,0)';
context.fillRect(10, 10, 55, 50);
context.fillStyle = 'rgba(0, 0, 250, 0.5)';
context.fillRect(30, 30, 55, 50);
</script>
</body>
</html>
</textarea>
Add below code to show the output from the editor
<div id="iframewrapper"></div>
Add “Run” button
After clicking the Run button, if there is any changes made in editor button will trigger to show the output
<button id="runButton" type="button" class="btn btn-default" onclick="submitTryit()">Run</button>
Add below script to enable the editor
Below script enable the editor for the id “editor” and enable the “autoCloseTags” option if the user type first tag of the element this will fill the remaining element automatically
<script>
// Initialize CodeMirror editor with a nice html5 canvas demo.
var editor = CodeMirror.fromTextArea(document.getElementById('editor'), {
mode: 'text/html',
autoCloseTags: true
});
submitTryit();
</script>
Add below function to render to show the output in to the id “iframewrapper”
function submitTryit(){
var text = editor.getValue();
var ifr = document.createElement("iframe");
ifr.setAttribute("frameborder", "0");
ifr.setAttribute("id", "iframeOutput");
document.getElementById("iframewrapper").innerHTML = "";
document.getElementById("iframewrapper").appendChild(ifr);
var ifrw = (ifr.contentWindow) ? ifr.contentWindow : (ifr.contentDocument.document) ? ifr.contentDocument.document : ifr.contentDocument;
ifrw.document.open();
ifrw.document.write(text);
ifrw.document.close();
};
Leave a Reply