javascript - Simulate backspace button JS -
i want create custom backspace button same logic "backspace" button on keyboard. use following code:
function backspace() { var e = jquery.event("keyup"); e.which = 8; // # 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 doesn't work. don't understand i'm doing wrong. spend lot of time problem, haven't solved yet. me, please.
addition @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>
Comments
Post a Comment