Html: Contenteditable how to detect before deleting element after pressing backspace?

I am making a text editor with <div contenteditable>. I want to prompt a confirmation message before the user deleting image element inside the editor. So when the user press backspace, before deleting the image element, there should be a prompt "Are you sure you want to delete the image?".

How can I do this?

38 thoughts on “Html: Contenteditable how to detect before deleting element after pressing backspace?”

  1. Event listener keydown can be added to that <div contenteditable> element. Keydown and keypress events takes place before the content is changed and event.preventDefault() can be used to stop the content before editing.

    window.onload = function(){
        if( event.key=='Backspace' ){
          //your condition check can be given here
          if( confirm('are you sure you want to delete') ){
      background-color: red;
    <div contenteditable="true" class="edit-elem" id="elem"></div>
  2. Is this what you want?

          alert('Are You Sure?');
      $(document).on('keyup','div', function(e){
         if(e.keyCode == '8'){
           alert('You have pressed backspace');
    <script src=""></script>
    <div contenteditable>
     <input type="file" class="image" name="image"/>
     <button type="button" class="remove">Remove</button>

Leave a Comment