Inserting Images in CKEditor 5: A Comprehensive Guide [ 3 ways to do that]

CKEditor is a powerful and widely used web-based WYSIWYG editor that provides users with a user-friendly interface for content creation. While CKEditor offers a range of built-in features and functionality, there may be instances where you need to insert custom HTML elements into your content. In this blog, we will explore how to insert custom HTML elements in CKEditor and enhance the editor’s capabilities to suit your specific needs.

There are different ways we can insert images into ckeditor5. As per my experience, I am sharing some of them from beginner to advance level.

  1. Inserting images via a source URL – using the plugin

    You will install and register the ckeditor5-image plugin in your editor initialization, this will create an icon in the toolbar where you will have the option to add an image via URL, as shown in
    below example.

    import { ImageInsert } from '@ckeditor/ckeditor5-image';
    
    ClassicEditor
        .create( document.querySelector( '#editor' ), {
            plugins: [ /* ... */ , ImageInsert ],
            toolbar: [ /* ... */ , 'insertImage' ]
        } )
    

    For more details, you can visit the CKEditor documentation

  2. Inserting images via a source URL – using the JavaScript codeSometimes you want to insert images not using the plugin but programmatically using JavaScript code. In this case, you may have images shown on page and you want the users to select them and they will be inserted in your CKeditor.
    
    
    function insertInEditor(imageUrl) {
           editor.execute("insertImage", { source: imageUrl });
    }

  3. Inserting images via a source URL – wrapping in some HTML elementThe above method (2) will simply insert the image in your editor, but if you need to wrap your image element in someĀ  tag, you can do it like this:
    
    
    function insertInEditor(imageUrl) {
      const position = editor.model.document.selection.getLastPosition();
    
      const docFrag = editor.model.change((writer) => {
        const paragraph = writer.createElement('paragraph');
        const image = writer.createElement('image');
        
        const docFrag = writer.createDocumentFragment();
    
        writer.append(image, docFrag);
        writer.append(paragraph, image);
    
        writer.setAttribute('src', imageUrl, image);
        writer.insert(image, position);
    
        return docFrag;
      });
    
      editor.model.insertContent(docFrag);
    }

    The same is the for other elements you can see more details here

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.