Mini editor (Part 1)

This is the first in a seven part series on how to make a WYSIWYG structure editor using javascript, jquery, erlang and couchDB.

This page provides a minimal example of how to set up a dynamically editable page using jQuery and contentEditable mode.

The principle of making this are simple, once understood you should easily able to make custom structure editor.

Step 1 - The HTML and CSS

First we need to define three regions on the page like this:

<body>
 <div id="header"></div>
 <div id="sidebar"></div>
 <div id="content"></div>
</body>

Next we add some styling. The styling makes the header and sidebar fixed and the content scrollable:

 body {
  padding-top:120px;   /* set this to some value greater than the 
                          height of the header */
  padding-left:100px;
  padding-right:320px; /* set the padding right to some value greater
                          than the width of the sidebar */
 }

 div#header {
  background-color:#aabbcc;
  position:fixed; /* <- important */
  padding-left:10px;
  top:0;
  left:0;
  width:500%;
  height:50px;  
 }

 div#sidebar{
  background-color:#bbccee;
  position:fixed;     /* <- important */
  padding-left:20px;
  padding-right:10px;
  top:50px;           /* set to the same at the height in the header */
  right:0;
  width:250px;  
  height:100%;
 }

 * html body{
  overflow:hidden;
 } 

 * html div.content{
  height:100%;
  overflow:auto;
 }

Adding an edit button to the sidebar

When the page is loaded we want to add an edit button to the sidebar. This button will toggle editing. The code is very simple:

This jquery code adds a button to the sidebar

Note1: The code examples here only show the important details of what's going on. Do view source to see all the details. For your convenience everything is in one file.

Note2: Life is too short for me to test this in all browsers. This works for me with the lastest version of Firefox. If you use some other brower and it doesn't work then I don't want to know.

$(document).ready(function(){
     editing=false;
     c = $("#content");
     b = $("<button>toggle edit</button>").click(toggle_edit);
     $("#sidebar").append(b);
     toggle_edit();
});

Then we define a the fucntion toggle_edit:

function toggle_edit()
{
    switch(editing){
    case true:
	c.get(0).contentEditable = false;
	c.css({background:"#eeeeee"});
	$("#header").html("You can now edit this document");
	editing=false;
	break;
    case false:
	c.get(0).contentEditable = true;
	c.css({background:"white"});
	editing=true;
	$("#header").html("This document is locked"};
        break;
    }
}

I've skipped a few of the less important details - do veiw source to see all the details, everything is on one file so it easy to see what's happening:

In part 2 I'll add styling to the editor