1

I am trying to create a syntax highlighted search field, where certain items are a particular color, bold, underline, etc. when I type. As I type, I would like the word in to become bold. This works with what I currently have, but when in is typed the cursor goes to the beginning of the div, and you can't type anything after the word in either. What can I do to fix this? You can see the jsfiddle here.

The JavaScript:

$(document).on("keyup", "#q", function(){
    var val = $(this).text();
    val = val.replace(/\sin\s/ig, " <b>in</b> ");
    $(this).html(val);
});

The HTML

<div id="q" name="q" class="form-control input-lg" contenteditable="true"></div>
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
  • Off the top of my head, the first thing I would try is get the cursor position at the beginning of the function and put it back there at the end of the function. – blex Mar 22 '15 at 17:33
  • See [`window.getSelection`](https://developer.mozilla.org/en-US/docs/Web/API/Window/getSelection) - specifically [`.getRangeAt`](https://developer.mozilla.org/en-US/docs/Web/API/Selection/getRangeAt) and [`.addRange`](https://developer.mozilla.org/en-US/docs/Web/API/Selection/addRange). – Toothbrush Mar 22 '15 at 17:43
  • I found this for getting the position: http://stackoverflow.com/a/3976125/1778465 and I found this for setting it http://stackoverflow.com/a/6249440/1778465, the second on is giving me this error though: `Uncaught IndexSizeError: Failed to execute 'setStart' on 'Range': The offset 12 is larger than or equal to the node's length (9).` – Get Off My Lawn Mar 22 '15 at 17:46
  • here is a possible working example: http://jsfiddle.net/cpatik/3QAeC/ – Get Off My Lawn Mar 22 '15 at 17:51

1 Answers1

0

With the rangy library I was able to accomplish this like this:

$(document).on("keyup", "#q", function(){
    var savedSel = rangy.saveSelection();
    var val = $(this).html();
    val = val.replace(/\sin\s/ig, " <b>in</b> ");
    $(this).html(val);
    rangy.restoreSelection(savedSel);
});
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338