Reputation: 1977
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?
Upvotes: 1
Views: 423
Reputation: 707396
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.
Upvotes: 1