Tryit Editor for HTML CSS JavaScript using CodeMirror

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;

Add HTML textarea

Below text area has the default html code in editor.

<textarea id=editor name=editor>
<!doctype html>
    <meta charset=utf-8>
    <title>HTML5 canvas demo</title>
    <style>p {font-family: monospace;}</style>
    <p>Canvas pane goes here:</p>
    <canvas id=pane width=300 height=200></canvas>
      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);

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

	// Initialize CodeMirror editor with a nice html5 canvas demo.
	var editor = CodeMirror.fromTextArea(document.getElementById('editor'), {
		mode: 'text/html',
		autoCloseTags: true

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 = "";
    var ifrw = (ifr.contentWindow) ? ifr.contentWindow : (ifr.contentDocument.document) ? ifr.contentDocument.document : ifr.contentDocument;;

Download Demo

Latest posts by W3TWEAKS (see all)


Leave a Reply

Your email address will not be published. Required fields are marked *