I have a contenteditable div with an id of “editable” in which I’ve simulated changing the character associated with a key event. You can see it in action here: http://jsfiddle.net/Ukkmu/66/
As you can see, no matter what alphanumeric key the user presses, the output string of “Singinme.” types out in the div. The spaces between the words in my var list are ignored. I’d like the output to include spaces, and read “Sing in me.” as it is currently written in the first line of my javascript code. I’ve gotten help to at least identify that my problem is in the insertTextAtCursor function, but how do I change that function to include space as an acceptable output character? Or, could I re-write my var list in a way that would type out as “Sing in me.” in the div?
For convenience, I’ve pasted the javascript below as well.
PS: I just found out that this is a browser issue. In Chrome, it is as I described it. In IE it works as I want it- “Sing in me.” with spaces. Any ideas how to make this work in Chrome? I don’t know if it works in firefox.
var list = "Sing in me.".split('');
function transformTypedCharacter(charStr) {
return (/[a-zA-Z]/).test(charStr) ? list.shift()||" " : charStr;
}
function insertTextAtCursor(text) {
var sel, range, textNode;
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0).cloneRange();
range.deleteContents();
textNode = document.createTextNode(text);
range.insertNode(textNode);
// Move caret to the end of the newly inserted text node
range.setStart(textNode, textNode.length);
range.setEnd(textNode, textNode.length);
sel.removeAllRanges();
sel.addRange(range);
}
} else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
range.pasteHTML(text);
}
}
$("#editable").keypress(function(evt) {
if (evt.which) {
var charStr = String.fromCharCode(evt.which);
var transformedChar = transformTypedCharacter(charStr);
if (transformedChar != charStr) {
insertTextAtCursor(transformedChar);
return false;
}
}
});
Chrome swallows the whitespace nodes. I can’t tell whether this is a bug or not since as it seems multiple browsers treat whitespace and empty nodes differently.
In your case a simple solution is using non-breaking spaces instead. That’s:
Or