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.
Edit: I have discovered that the code does not work on the mobile phone Chrome browser because, on the mobile phone browser, e.key is Unidentified. On the mobile phone browser, e.keydoes not detect which key was pressed. Perhaps the mobile phone browser does not support e.key, So what other way could I use to determine which key is pressed on the mobile browser?
$('#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 class="word">Hello</span>
<span class="word">World</span>
</div>
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 class="word">Hello</span>
<span class="word">World</span>
</div>
$(document).ready(function(){
$('.word').on('keyup',function(e) {
if(e.key == "Backspace" || e.key == "Delete"){
$(this).remove();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div contenteditable="false" id="section">
<span contenteditable="true" class="word">Hello</span>
<span contenteditable="true" class="word">World</span>
</div>