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(){
      document.getElementById("elem").addEventListener('keydown',function(event){
        if( event.key=='Backspace' ){
          //your condition check can be given here
          if( confirm('are you sure you want to delete') ){
            return;
          }else{
            event.preventDefault();      
          }
    
        } 
      });
    }
    .edit-elem{
      background-color: red;
    }
    <div contenteditable="true" class="edit-elem" id="elem"></div>
    Reply
  2. Is this what you want?

    $(document).ready(function(){
      $('.remove').click(function(e){
          e.preventDefault();
          alert('Are You Sure?');
      });
      
      $(document).on('keyup','div', function(e){
         console.log(e.keyCode);
         if(e.keyCode == '8'){
           alert('You have pressed backspace');
         }
      
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div contenteditable>
     <input type="file" class="image" name="image"/>
     <button type="button" class="remove">Remove</button>
    </div>
    Reply

Leave a Comment