6

I want to create a custom backspace button with the same logic as "backspace" button on a keyboard. I use the following code:

function backSpace()
{
    var e = jQuery.Event("keyup");
    e.which = 8; // # Some key code value
    e.keyCode = 8;
    $("mainDiv").trigger(e);
}
<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="styles.css" type="text/css" media="screen" />
        <script src="formulas.js"></script>
        <script src="http://code.jquery.com/jquery-1.11.3.js"></script>
        <meta name="viewport" content="width=device-width initial-scale=1.0 maximum-scale=1.0 user-scalable=no"/>
    </head>

    <button onclick="backSpace()">backSpace</button>
    <body id="main" spellcheck="false">
        <div id = "mainDiv" contenteditable="true"></div>
    </body>
</html>

But it doesn't work. I don't understand what I'm doing wrong. I spend a lot of time for this problem, but I haven't solved it yet. Help me, please.

Nikita Ermolenko
  • 2,139
  • 2
  • 19
  • 41

7 Answers7

5

This code works fine for me. You can clear letter by letter at caret position or clear a selection

var textbox = document.getElementById('textbox');

function backspace()
{
var ss = textbox.selectionStart;
var se = textbox.selectionEnd;
var ln  = textbox.value.length;

var textbefore = textbox.value.substring( 0, ss );    //text in front of selected text
var textselected = textbox.value.substring( ss, se ); //selected text
var textafter = textbox.value.substring( se, ln );    //text following selected text

if(ss==se) // if no text is selected
{
textbox.value = textbox.value.substring(0, ss-1 ) + textbox.value.substring(se, ln );
textbox.focus();
textbox.selectionStart = ss-1;
textbox.selectionEnd = ss-1;
}
else // if some text is selected
{
textbox.value = textbefore + textafter ;
textbox.focus();
textbox.selectionStart = ss;
textbox.selectionEnd = ss;
}

}
<textarea id="textbox"></textarea>
<div class="button" onclick="backspace()" > BACKSPACE_BUTTON </div>

Hope that helps!

T30
  • 11,422
  • 7
  • 53
  • 57
JPK
  • 95
  • 1
  • 8
3

Solution for input.

backSpace = function ()
{
    var str= $("#text_input").val();
    var position = document.getElementById('text_input').selectionStart-1;

    str = str.substr(0, position) + '' + str.substr(position + 1);
    $("#text_input").val(str);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="backSpace()">backSpace</button>
<input type='text' id='text_input' value='123456789'/>

Hope this helps.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
3

Addition to @CosLu's Answer

JSBin Here also

function backSpace() {
  p = document.getElementById("mainDiv");
  c = getCaretPosition(p);
  console.log(getCaretPosition(p));
  str = $("#mainDiv").html();
  if (c > 0 && c <= str.length) {
    $("#mainDiv").focus().html(str.substring(0, c - 1) + str.substring(c, str.length));

    p.focus();
    var textNode = p.firstChild;
    var caret = c - 1; 
    var range = document.createRange();
    range.setStart(textNode, caret);
    range.setEnd(textNode, caret);
    var sel = window.getSelection();
    sel.removeAllRanges();
    sel.addRange(range);
  }
}

$.fn.setCursorPosition = function(pos) {
  this.each(function(index, elem) {
    if (elem.setSelectionRange) {
      elem.setSelectionRange(pos, pos);
    } else if (elem.createTextRange) {
      var range = elem.createTextRange();
      range.collapse(true);
      range.moveEnd('character', pos);
      range.moveStart('character', pos);
      range.select();
    }
  });
  return this;
};

function getCaretPosition(editableDiv) {
  var caretPos = 0,
    sel, range;
  if (window.getSelection) {
    sel = window.getSelection();
    if (sel.rangeCount) {
      range = sel.getRangeAt(0);
      if (range.commonAncestorContainer.parentNode == editableDiv) {
        caretPos = range.endOffset;
      }
    }
  } else if (document.selection && document.selection.createRange) {
    range = document.selection.createRange();
    if (range.parentElement() == editableDiv) {
      var tempEl = document.createElement("span");
      editableDiv.insertBefore(tempEl, editableDiv.firstChild);
      var tempRange = range.duplicate();
      tempRange.moveToElementText(tempEl);
      tempRange.setEndPoint("EndToEnd", range);
      caretPos = tempRange.text.length;
    }
  }
  return caretPos;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <script src="http://code.jquery.com/jquery-1.11.3.js"></script>
</head>

<body>
  <button onclick="backSpace()">backSpace</button>
  <div id="mainDiv" contenteditable="true">aahahtext</div>
</body>

</html>
shyammakwana.me
  • 5,562
  • 2
  • 29
  • 50
  • Thanks again! But i have trouble, when insert special symbol. When I insert "sigma" and then click "backSpace" button i see wrong logic (function delete wrong character). To right logic I have to set caret position manually and then click "backSpace". See attached. http://jsbin.com/kefutuvuci/edit?html,js,output – Nikita Ermolenko Sep 30 '15 at 12:47
  • it's because when you insert sigma, carat position in `backspace()` resets to 1. – shyammakwana.me Sep 30 '15 at 13:31
  • @shyammakwana.me : although its for content editable, it doesn't work for lets say tag :( – Shashank Vivek Apr 26 '18 at 11:06
1

Just update your js to make it work. I have found a snippet to look for the caret position here: Get caret position in contentEditable div

Note that the following code assumes:

  • There is always a single text node within the editable and no other nodes

  • The editable div does not have the CSS white-space property set to pre

function backSpace()
{
    p = document.getElementById ("mainDiv");
    c = getCaretPosition(p);
    str= $("#mainDiv").html();
    if(c>0 && c<=str.length){
      $("#mainDiv").html(str.substring(0,c-1)+ str.substring(c,str.length));
    }
}

function getCaretPosition(editableDiv) {
  var caretPos = 0,
sel, range;
  if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
  range = sel.getRangeAt(0);
  if (range.commonAncestorContainer.parentNode == editableDiv) {
    caretPos = range.endOffset;
  }
}
  } else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
if (range.parentElement() == editableDiv) {
  var tempEl = document.createElement("span");
  editableDiv.insertBefore(tempEl, editableDiv.firstChild);
  var tempRange = range.duplicate();
  tempRange.moveToElementText(tempEl);
  tempRange.setEndPoint("EndToEnd", range);
  caretPos = tempRange.text.length;
}
  }
  return caretPos;
}
<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="styles.css" type="text/css" media="screen" />
        <script src="formulas.js"></script>
        <script src="http://code.jquery.com/jquery-1.11.3.js"></script>
        <meta name="viewport" content="width=device-width initial-scale=1.0 maximum-scale=1.0 user-scalable=no"/>
    </head>

    
    <body id="main" spellcheck="false">
        <button onclick="backSpace()">backSpace</button>
        <div id = "mainDiv" contenteditable="true">aahahtext</div>
    </body>
</html>
Community
  • 1
  • 1
nowhere
  • 1,558
  • 1
  • 12
  • 31
1

That would be a solution:

http://jsfiddle.net/nezkbws7/2/

function backSpace()
{
  var txt = $("#mainDiv").text();
  txt = txt.substr(0,txt.length-1)
  $("#mainDiv").text(txt);
}

I created the backspace functionality manually, not with copying the event.

jacksbox
  • 911
  • 1
  • 11
  • 24
1

Use document.execCommand('delete') to send a backspace:

document.querySelector('#whatever-element').focus(); // focus if needed
document.execCommand('delete');
Jo Liss
  • 30,333
  • 19
  • 121
  • 170
0
$("#sup").on("keydown", function (e) {
if (e.which == 8 || e.keyCode === 8) {
selection = window.getSelection();
selection.modify("extend", "backward", "character");
selection.deleteFromDocument();
  }
});

the caret needs to exist inside the text area for it to work.