jQuery val() not working with Caret logic in Chrome
If you save and add to the scrollLeft
position of the input, it will update and keep the typed character in view. Although, it fails if you click and start typing in the middle of the input.
I updated the second input demo with the code below. Also note that the input and test span that is added should have the same font size.
input_2.bind('keydown.keyboard', function(e) { var key = "", current_val = input_2.val(), pos = input_2.caret(), start_pos = pos.start, end_pos = pos.end, scroll = $(this).scrollLeft(); // some mapped keys switch (e.which) { // e key case 69: key = "ε"; e.preventDefault(); break; // f key case 70: key = "φ"; e.preventDefault(); break; // z key case 90: key = "ζ"; e.preventDefault(); break; // a key case 65: key = "α"; e.preventDefault(); break; } if (key !== '') { var test = $('<span class="test"> ' + key + '</span>').appendTo('body'); scroll += test.width(); test.remove(); } input_2.val(current_val + key); //Insert/Replace text at caret then restore caret input_2.value = current_val.substr(0, start_pos) + key + current_val.substr(end_pos, current_val.length); input_2.caret(start_pos + key.length, start_pos + key.length); if (key !== '') { $(this).scrollLeft(scroll); }});
Update: the scrollLeft position seemed to be a bit off, so if you add a
inside the span with the character, it works out much better (updated demo)