0

I need to implement the backspace key behaviour so that my cursor is placed one position to the left without the user pressing the Backspace key, but rather after a string is added programmatically inside my (contenteditable) div, I need the cursor to move automatically one position left. I tried adding \b to my string, with no success.

How can I achieve this behaviour (preferably using JavaScript)?

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Crista23
  • 3,203
  • 9
  • 47
  • 60

2 Answers2

0

You can easily workaround this by injecting a browser event into your content editable. I am showing an example using the left arrow key because you wrote that you want to move the cursor, which I would expect is what you want, because Backspace would delete a character. If you want to delete then replace the keycode for left with backspace.

Here is how it's done using jQuery:

var ev = jQuery.Event("keydown"); // Creates a new keydown event
ev.keyCode = $.ui.keyCode.LEFT; // Sets the event keyCode to be the left arrow button
$('#contentEditableContainer').trigger(ev);

To include jQuery:

<head>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
Konstantin Dinev
  • 34,219
  • 14
  • 75
  • 100
  • Hi Konstantin! Thank you for your answer. I am new to jQuery and using jQuery 1.6.4 I get an error saying that jQuery is undefined. What should I include? Many thanks! – Crista23 Oct 15 '12 at 10:57
  • Thank you for your answer, but still not getting the expected result. As I found on another SO post, it seems that this solution does NOT simulate a natural keypress event on the HTML element. This method only triggers the keydown event, it does not replicate the user going into the element and pressing that key as I need. – Crista23 Oct 16 '12 at 07:44
  • @Crista23 you can still trigger the event on the element that you want and it would be treated as a regular javascript event on this element as if it was focused. – Konstantin Dinev Oct 16 '12 at 08:04
0

Here is the function that I use, make sure you include jQuery. Just call this function with a id to the text box you want the backspace to act:

function backSpace(id){
var txt = $(id);
var startPos = txt[0].selectionStart;
var endPos = txt[0].selectionEnd;
var scrollPos = txt[0].scrollTop;
console.log("start: " + startPos + " end: " + endPos + " scrollPos: " + scrollPos);
if (endPos - startPos > 0){
    txt.val(txt.val().slice(0, startPos) + txt.val().slice(endPos, 100));
}else if (endPos > 0){
    txt.val(txt.val().slice(0, startPos-1) + txt.val().slice(startPos, 100));
}else{
    startPos = txt.val().length+1;
}
txt.focus();
txt[0].setSelectionRange(startPos-1,startPos-1);
}