Question

I have a div that is contenteditable with the id of "editable." I want the end result to be that a user types, but rather than the physical key event, a pre-determined message appears.

For example, if the pre-determined message is the word, "Sing", then no matter what letter the user types first, the first letter to appear is "S", on the second key press, an "i" would appear, and so on.

I've found code on this forum that simulates changing the character associated with a key event, and I've modified the code to achieve the "S" from my example. I've pasted the code below and created it here: http://jsfiddle.net/Ukkmu/61/

This code, of course, gives me the "S" infinite times. Where I'm stuck is performing this function only once, then calling another function for the "i", then the "n" and so on.
I've gotten one possible lead on a toggle function that I suppose may work, but have been unable to discern how to apply it to my code.

function transformTypedCharacter(charStr) {
  return /[a-z]/.test(charStr) ? "S" : /[A-Z]/.test(charStr) ? "S" :   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;
    } 
  }
});
Was it helpful?

Solution

Use this instead:

var list = "Sing".split('');
function transformTypedCharacter(charStr) {
    return /[a-zA-Z]/.test(charStr) ? list.shift()||" " : charStr;
}

However I'm not sure whether this is really the best approach, as it might be possible that transformTypedCharacter is not called in a linear fashion respective to the expected output string. If you hit backspace, you might return some characters twice, and if you hit umlauts etc the would be inserted somewhere in your result.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top