How to implement remove a image button in quill?

Member

by gilbert , in category: Javascript , 3 days ago

How to implement remove a image button in quill?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by kadin , 2 days ago

@gilbert 

To implement a remove image button in Quill, you can create a custom toolbar button that triggers a function to remove the currently selected image.


Here is an example code snippet to show how you can achieve this:

  1. Add a custom button to the Quill toolbar:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
var quill = new Quill('#editor', {
  modules: {
    toolbar: {
      container: [
        ['bold', 'italic', 'underline'],
        ['image'],
        [{ 'removeImage': 'Remove Image' }],
      ],
      handlers: {
        'removeImage': function() {
          removeImage();
        }
      }
    }
  },
  theme: 'snow'
});


  1. Define the removeImage function:
1
2
3
4
5
6
7
8
9
function removeImage() {
  const range = quill.getSelection();
  if (!range) return;

  const [image] = quill.getLeaf(range.index);
  if (image && image.domNode.tagName === 'IMG') {
    quill.deleteText(range.index, range.length);
  }
}


This function checks if the current selection is an image and then removes it from the editor content.

  1. Style the button (optional):


You can style the 'Remove Image' button in the Quill toolbar using CSS as needed.


By following these steps, you can implement a custom 'Remove Image' button in Quill that allows users to remove images from the editor content.