Previously, we created a javascript keyboard buffer and next I’d like to process that buffer to edit text in a static html page.
Given the following simple html:
<div id="keyboardBufferTest"> Spam and eggs </div>
I would like the keyboard buffer to modify the text inside that div element.
The following JavaScript function will read the buffer and modify the innerHTML of a named element:
// // append a single character from BUFFER to an elements innerHTML var bp = 0; var ENTITIES = { 13 : ' ', 38 : '&', 60 : '<', 62 : '>', 222 : "'" } function appendChar(el) { if (BUFFER[bp] == 8) { appendBackspace(el); } else if (BUFFER[bp] in ENTITIES) { el.innerHTML += ENTITIES[BUFFER[bp]]; } else { el.innerHTML += String.fromCharCode(BUFFER[bp]); } bp++; } function appendBackspace(el) { var endpointer = 1; var plength = el.innerHTML.length; for (var i in ENTITIES) { var entity = ENTITIES[i]; var entityCheck = el.innerHTML.substr(plength - entity.length) if (entity == entityCheck) { endpointer = entity.length; break; } } el.innerHTML = el.innerHTML.substr(0, plength - endpointer); }
The BUFFER contains unicode values that need to be encoded into readable characters. In the above example the builtin String.fromCharCode() function is used. The appendChar(el) function simply processes one element at a time from the BUFFER and maintains a buffer pointer so that the BUFFER can be safely read while new keystrokes are recorded.
There is a very simply ENTITIES hash that serves only to maintain basic HTML encoding.
To use this function, simply pass in the element you want modified. This function can be added to the onkey event handler so that changes to a static html page will appear as you type them.
Next, I’d like to add a buffer replay such that changes to the html can be viewed multiple times exactly as they were typed (keystroke by keystroke).