1

my html:

<div id="search" contenteditable="true"></div>

my js:

var clrz = ['#ad13f6','#3f00d0','#00ff7e']

$('#search').bind('input', function() {

    var s = $('#search').text();
    var a = s.split('');
    for (var i = 0; i < a.length; i++) {
        var ran = Math.floor(Math.random()*3);
        var clr = clrz[ran];
        a[i] = '<span style="color:'+clr+';">' + a[i] +'</span>'
    };
    $('#search').html(a);

});

if I remove the last line ( $('#search').html(a) ) which rewrites the div, and I log the arrary ( a ) to the console it comes out in order. But when I try to rewrite it with .html(a) it comes out backwards ????

here's a fiddle:http://jsfiddle.net/kAvEm/

any ideas why?

Nick Briz
  • 1,917
  • 3
  • 20
  • 34
  • 1
    Because the cursor remains at the front all the time, so every time when you type a char, it adds to the beginning of the string. – zs2020 Sep 03 '13 at 05:31
  • It might b because you are using a random function so the order might change everytime. Could you define "in order" and "backwards"? – Vandesh Sep 03 '13 at 05:31
  • possible duplicate of [How to move cursor to end of contenteditable entity](http://stackoverflow.com/questions/1125292/how-to-move-cursor-to-end-of-contenteditable-entity) – Ja͢ck Sep 03 '13 at 05:34

1 Answers1

1

Each time you hit a keystroke and cause the contents of #search to get rewritten, the insertion cursor is set back to the beginning of the div so each new key you type goes at the beginning of the div.

If you hit the "end" key after you type each key, you can see that it avoids the problem. If you really want to be rewriting what is being typed, then you will need to save the cursor position before you rewrite the data and then restore it after rewriting the data.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • thnx so much! didn't even notice the carrot position && thnx @Jack moving the carrot within a contenteditable element would have been my next question :) – Nick Briz Sep 03 '13 at 05:45