Reputation: 474
I have seen other questions like this but it is a little unclear what the correct way to do each is. My assumption was to move the cursor to the front of a ContentEditable, you would simply put focus on the element. To move the cursor to the back would require some sort of polyfil solution.
Fiddle: http://jsfiddle.net/ys04jkth/
The intended functionality in my fiddle is to move the cursor across a text box which contains a "token" (div) in the middle of it. When focus is on the token, the user can delete it, or continue moving left or right with their arrow keys. On of the common solutions seen in the other questions which ask how to move to the end of a ContentEditable is the function below, which I try to use when the user is focused on the token an clicks the left arrow key:
function placeCaretAtEnd(el) {
el.focus();
if (typeof window.getSelection != "undefined"
&& typeof document.createRange != "undefined") {
var range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (typeof document.body.createTextRange != "undefined") {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.collapse(false);
textRange.select();
}
}
When the user is focused on the token and they hit the right arrow key, I try to focus on the next span over, assuming it would focus the cursor at the front. I am seeing weird behavior where in both cases, the first letter is skipped. Any insight into why this is happening?
Thanks.
Upvotes: 2
Views: 2017
Reputation: 3397
In your keydown function, you change your event target for the next (or previous) element when you reach the end (or the beginning) of it.
What is going on after you change the target? The keydown default behavior. So if you were typing the right arrow, you reach the end, you change your target... and your cursor is moved to the right since it is the default behavior.
What is the solution? You can prevent the default behavior using return false
. So the code for the right arrow in your keydown event would be something like this:
if (event.keyCode == 39) { //Right arrow
var nextSpan = selectedToken.next();
if (nextSpan.length) {
nextSpan.focus();
selectedToken.removeClass('selectedToken');
}
return false;
}
Here is your updated fiddle.
Upvotes: 1