When any of the characters of 'Hello' or 'World' is deleted in a contenteditable
div, the entire word should be deleted.
This code below works on Chrome Version 102.0.5005.115 (Official Build) (64-bit)
on laptop but does not work on Chrome Version 102.0.5005.5005.125
on Android
mobile phone. What is the correct way of achieving the solution this with jQuery or JS?
$('#div-editor').keyup(function(e) {
var $target = $(document.getSelection().anchorNode).closest(".word");
$(".word").each(function(){
if (["Delete", "Backspace"].includes(e.key)) {
$target.remove();
e.preventDefault();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div contenteditable="true" id = "div-editor" >
<span >Hello</span>
<span >World</span>
</div>
CodePudding user response:
Try below code snippet
$('#section .word').attr("contenteditable", true);
$(document).on("keyup","#section .word",function(e) {
if (["Delete", "Backspace"].includes(e.key)) {
$(this).remove();
e.preventDefault();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="section">
<span >Hello</span>
<span >World</span>
</div>
CodePudding user response:
Just need to add conditions of backspace and delete.
$('.word').on('DOMSubtreeModified',function(e) {
$(this).remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div contenteditable="true" id="section">
<span >Hello</span>
<span >World</span>
</div>