0

I'm working on "Add comment box" with some features like change [b]text[/b] to be text with bold style and so on. The problem is when the str.replace operation in javascript done the cursor which is in the writing area come back to the start position.

$('#comment').keyup(function () {
    var str = document.getElementById("comment").innerHTML;
    if (str.indexOf('[b]') >= 0 && str.indexOf('[/b]') >= 0) {
        var start_pos = str.indexOf('[b]') + 3;
        var end_pos = str.indexOf('[/b]', start_pos);
        var text_to_get = str.substring(start_pos, end_pos)
        res = str.replace("[b]" + text_to_get + "[/b]", "<b>" + text_to_get + "</b>");
        document.getElementById("comment").innerHTML = res;
    }
});
isherwood
  • 58,414
  • 16
  • 114
  • 157
Revolution
  • 47
  • 2
  • 2
    This isn't a question about `str.replace`, but the behavior of `innerHTML`. – isherwood Nov 30 '15 at 21:39
  • Does [this question and answer](http://stackoverflow.com/questions/7745867/how-do-you-get-the-cursor-position-in-a-textarea) help? – Blazemonger Nov 30 '15 at 21:39
  • Possible duplicate of [Maintain cursor position in contenteditable div](http://stackoverflow.com/questions/16194364/maintain-cursor-position-in-contenteditable-div) – isherwood Nov 30 '15 at 21:40

2 Answers2

0

Have you tried putting the focus back on the element? Usually the browsers(Except IE) puts the cursor back to it`s original location once it is brought back into focus.Since you are using jquery:

$("#yourID").focus()

thepiyush13
  • 1,321
  • 1
  • 8
  • 9
0

I think you should use a lexter/parser instead to convert bbcode to HTML (unless the reason is that you want to learn by doing).

Here's one that might work for you. It has support for the default bbcode blocks and makes it possible to define you own.

<head>
  <!-- Optional styling for .xbbcode-* classes -->
  <link rel="stylesheet" type="text/css" href="xbbcode.css">
</head>
<body>
  <script src="xbbcode.js"></script>
  <script>
    var text = document.getElementById("comment").innerHTML;
    var result = XBBCODE.process({
      text: text,
      removeMisalignedTags: false,
      addInLineBreaks: false
    });
    console.error("Errors", result.error);
    console.dir(result.errorQueue);
    console.log(result.html);  //=> <span class="xbbcode-b">Hello world</span>
  </script>
</body>
Linus Oleander
  • 17,746
  • 15
  • 69
  • 102