Use CKEditor in Your Project with jQuery

By Maulik Paghdal

11 Aug, 2024

•  8 minutes to Read

Use CKEditor in Your Project with jQuery

Introduction

Adding a rich text editor to your web application can significantly enhance user experience. CKEditor, one of the most popular rich text editors, offers robust features and an easy integration process. In this guide, we'll demonstrate how to integrate CKEditor into your project using jQuery, explore advanced configuration options, and provide practical implementation examples.

Why CKEditor?

CKEditor provides numerous benefits for developers and end users alike, including:

  • Customizability: Tailor the editor's toolbar, UI, and behavior to fit your application's needs with extensive configuration options.
  • Cross-browser Support: Works seamlessly across all major browsers (Chrome, Firefox, Safari, Edge) with consistent behavior and appearance.
  • Rich Plugins Ecosystem: Extend functionality with plugins for embedding media, adding tables, syntax highlighting, mathematical formulas, and more.
  • Accessibility Compliance: Built with WCAG 2.1 accessibility standards in mind, ensuring all users can interact with your content.
  • Language Support: Offers localization in over 70 languages out of the box.
  • Mobile-friendly: Responsive design works on various screen sizes and supports touch interactions.

Setting Up CKEditor with jQuery

Follow these detailed steps to integrate CKEditor into your project:

1. Download CKEditor

Visit the official CKEditor website and download the version best suited for your project. CKEditor offers several builds:

Build TypeDescriptionBest For
ClassicTraditional UI with a toolbar at the topContent management systems, admin panels
InlineAppears when the editable area is clickedModern, distraction-free interfaces
BalloonFloating toolbar appears near the selectionBlog posts, comments sections
DocumentFull-featured document editingLong-form content, documentation

Alternatively, use a CDN link for quick integration without downloading files locally.

2. Include CKEditor and jQuery in Your Project

Add the following scripts to your HTML file:

<!-- jQuery library -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>

<!-- CKEditor from CDN (standard package with common plugins) -->
<script src="https://cdn.ckeditor.com/4.20.0/standard/ckeditor.js"></script>

<!-- Alternatively, if you downloaded CKEditor locally -->
<!-- <script src="path/to/your/ckeditor/ckeditor.js"></script> -->

Note: When using CKEditor in a production environment, consider specifying an integrity hash for the CDN link to enhance security.

3. Create an HTML Textarea

Add a textarea element where you want the editor to appear:

<div class="editor-container">
    <label for="editor1">Content Editor:</label>
    <textarea id="editor1" name="editor1" rows="10" cols="80">
        <p>This is the initial content that will appear in the editor.</p>
    </textarea>
</div>

4. Initialize CKEditor

Use jQuery to initialize CKEditor with basic configuration:

<script>
  $(document).ready(function() {
    // Basic initialization
    CKEDITOR.replace('editor1');
    
    // You can also use jQuery selector directly
    // CKEDITOR.replace($('#editor1')[0]);
    
    // Confirm the editor has been initialized
    CKEDITOR.on('instanceReady', function(evt) {
      console.log('CKEditor instance "' + evt.editor.name + '" is ready!');
    });
  });
</script>

5. Handle Form Submission

When your form is submitted, CKEditor's content isn't automatically synchronized with the textarea. Handle this with:

<form id="myForm" method="post" action="/submit">
  <textarea id="editor1" name="editor1"></textarea>
  <button type="submit">Submit</button>
  
  <script>
    $(document).ready(function() {
      CKEDITOR.replace('editor1');
      
      // Update textarea before form submission
      $('#myForm').on('submit', function() {
        for (var instanceName in CKEDITOR.instances) {
          CKEDITOR.instances[instanceName].updateElement();
        }
        console.log("Form submitted with editor content:", $('#editor1').val());
      });
    });
  </script>
</form>

Customizing CKEditor

CKEditor offers extensive customization options to match your application's requirements:

Basic Configuration

CKEDITOR.replace('editor1', {
  // Customize toolbar groups and buttons
  toolbar: [
    { name: 'document', items: ['Source', '-', 'Save', 'NewPage', 'Preview', 'Print', '-', 'Templates'] },
    { name: 'clipboard', items: ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo'] },
    { name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat'] },
    '/',  // Line break in toolbar
    { name: 'paragraph', items: ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'] },
    { name: 'links', items: ['Link', 'Unlink', 'Anchor'] },
    { name: 'insert', items: ['Image', 'Table', 'HorizontalRule', 'SpecialChar'] },
    { name: 'styles', items: ['Styles', 'Format', 'Font', 'FontSize'] },
    { name: 'colors', items: ['TextColor', 'BGColor'] },
    { name: 'tools', items: ['Maximize', 'ShowBlocks'] }
  ],
  
  // Editor UI properties
  height: 300,
  width: '100%',
  uiColor: '#f7f7f7',
  
  // Content styling
  contentsCss: ['body {font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 14px;}'],
  
  // Set language
  language: 'en',
  
  // Remove plugins
  removePlugins: 'elementspath,scayt,wsc',
  
  // Enable native browser spell checking
  disableNativeSpellChecker: false,
});

Creating Custom Toolbar Configurations

For different usage scenarios, you might want simplified toolbar configurations:

// Minimal configuration for simple text editing
const minimalConfig = {
  toolbar: [
    { name: 'basicstyles', items: ['Bold', 'Italic', 'Link'] }
  ],
  height: 100,
  removePlugins: 'elementspath,scayt,wsc,image,table,horizontalrule,specialchar'
};

// Standard configuration for general use
const standardConfig = {
  toolbar: [
    { name: 'styles', items: ['Format'] },
    { name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike'] },
    { name: 'paragraph', items: ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent'] },
    { name: 'links', items: ['Link', 'Unlink'] },
    { name: 'insert', items: ['Image', 'Table'] }
  ],
  height: 250
};

// Full-featured configuration for advanced users
const advancedConfig = {
  // More extensive configuration here
};

// Initialize editors with different configurations
$(document).ready(function() {
  CKEDITOR.replace('commentEditor', minimalConfig);
  CKEDITOR.replace('articleEditor', standardConfig);
  CKEDITOR.replace('documentEditor', advancedConfig);
});

Implementing Custom Styles Dropdown

Add your own styles dropdown options to provide consistent formatting options:

CKEDITOR.replace('editor1', {
  // Other configuration...
  
  stylesSet: [
    { name: 'Heading 1', element: 'h1', attributes: { 'class': 'heading-large' } },
    { name: 'Heading 2', element: 'h2', attributes: { 'class': 'heading-medium' } },
    { name: 'Code Block', element: 'pre', attributes: { 'class': 'code-block' } },
    { name: 'Info Box', element: 'div', attributes: { 'class': 'info-box' } },
    { name: 'Warning Box', element: 'div', attributes: { 'class': 'warning-box' } },
    { name: 'Inline Code', element: 'code' },
    { name: 'Citation', element: 'cite' }
  ]
});

Adding CKEditor Plugins

CKEditor's functionality can be extended with plugins for various features:

Installing Plugin from the Official Repository

// 1. Include the plugin JS file
// <script src="path/to/ckeditor/plugins/codesnippet/plugin.js"></script>

// 2. Configure CKEditor to use the plugin
CKEDITOR.replace('editor1', {
  extraPlugins: 'codesnippet',
  codeSnippet_theme: 'monokai_sublime',
  
  // Add the plugin's buttons to the toolbar
  toolbar: [
    // Other toolbar groups...
    { name: 'insert', items: ['Image', 'Table', 'CodeSnippet'] }
  ]
});

Creating a Simple Custom Plugin

You can also create custom plugins for specialized functionality:

// Create a custom plugin
CKEDITOR.plugins.add('timestamp', {
  init: function(editor) {
    // Add a command that can be executed to insert a timestamp
    editor.addCommand('insertTimestamp', {
      exec: function(editor) {
        const now = new Date();
        const timestamp = now.toLocaleString();
        editor.insertHtml('<span class="timestamp">' + timestamp + '</span>');
      }
    });
    
    // Add a button to the toolbar
    editor.ui.addButton('Timestamp', {
      label: 'Insert Timestamp',
      command: 'insertTimestamp',
      toolbar: 'insert',
      icon: 'https://example.com/timestamp-icon.png' // Replace with your icon path
    });
  }
});

// Use the custom plugin
CKEDITOR.replace('editor1', {
  extraPlugins: 'timestamp',
  toolbar: [
    // Other toolbar groups...
    { name: 'insert', items: ['Image', 'Table', 'Timestamp'] }
  ]
});

Implementing Word Count Feature

CKEDITOR.replace('editor1');

// Create UI for word/character count
$('<div id="editorStats" style="margin-top:10px;">' +
  '<span id="wordCount">Words: 0</span> | ' +
  '<span id="charCount">Characters: 0</span>' +
  '</div>').insertAfter('#editor1');

// Update counts when content changes
CKEDITOR.instances.editor1.on('change', function() {
  updateCounts();
});

// Also update on initial load
CKEDITOR.instances.editor1.on('instanceReady', function() {
  updateCounts();
});

function updateCounts() {
  const content = CKEDITOR.instances.editor1.getData();
  
  // Get text without HTML tags
  const div = document.createElement('div');
  div.innerHTML = content;
  const text = div.textContent || div.innerText || '';
  
  // Count words (split by whitespace and filter empty strings)
  const words = text.split(/\s+/).filter(function(word) {
    return word.length > 0;
  });
  
  // Update UI
  $('#wordCount').text('Words: ' + words.length);
  $('#charCount').text('Characters: ' + text.length);
}

Multiple Editor Instances with Different Configurations

<div class="editor-area">
  <h3>Post Title</h3>
  <textarea id="titleEditor" name="title"></textarea>
  
  <h3>Post Content</h3>
  <textarea id="contentEditor" name="content"></textarea>
  
  <h3>Short Description</h3>
  <textarea id="descriptionEditor" name="description"></textarea>
</div>

<script>
  $(document).ready(function() {
    // Simple editor for title - just basic formatting
    CKEDITOR.replace('titleEditor', {
      toolbar: [['Bold', 'Italic', 'Underline']],
      height: 100,
      enterMode: CKEDITOR.ENTER_BR,
      removePlugins: 'elementspath,uploadimage,image,table',
      resize_enabled: false
    });
    
    // Full-featured editor for main content
    CKEDITOR.replace('contentEditor', {
      // Full configuration with all features
      height: 400
    });
    
    // Medium complexity editor for description
    CKEDITOR.replace('descriptionEditor', {
      toolbar: [
        { name: 'basicstyles', items: ['Bold', 'Italic', 'Strike'] },
        { name: 'paragraph', items: ['NumberedList', 'BulletedList'] },
        { name: 'links', items: ['Link', 'Unlink'] }
      ],
      height: 150,
      wordcount: {
        maxWordCount: 100,
        maxCharCount: 500
      },
      removePlugins: 'image,table,horizontalrule,specialchar,uploadimage'
    });
    
    // Form submission handler for all editors
    $('form').on('submit', function() {
      for (var instance in CKEDITOR.instances) {
        CKEDITOR.instances[instance].updateElement();
      }
    });
  });
</script>

Optimizing for Mobile Devices

CKEDITOR.replace('editor1', {
  // Responsive toolbar configuration for different screen sizes
  toolbar: [
    { name: 'basicstyles', items: ['Bold', 'Italic', 'Underline'] },
    { name: 'paragraph', items: ['NumberedList', 'BulletedList'] },
    { name: 'links', items: ['Link'] },
    { name: 'tools', items: ['Maximize'] }
  ],
  
  // Mobile-friendly settings
  width: '100%', // Responsive width
  height: 200,   // Shorter height for mobile
  removePlugins: 'elementspath,resize', // Remove unnecessary UI elements
  
  // Touch-friendly configuration
  skin: 'moono-lisa', // Mobile-friendly skin
  toolbarCanCollapse: true, // Allow toolbar collapse on small screens
  
  // Detect mobile devices and adjust configuration
  on: {
    instanceReady: function(evt) {
      const editor = evt.editor;
      
      // Check if mobile device
      if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
        // Apply mobile-specific settings
        editor.resize('100%', 150);
        
        // Increase button sizes for touch
        $('.cke_button').css({
          'padding': '10px',
          'margin': '5px'
        });
      }
    }
  }
});

Conclusion

Integrating CKEditor with jQuery offers a powerful, customizable rich text editing experience for your web applications. With proper configuration and implementation best practices, CKEditor can be tailored to meet any project requirement, from simple commenting systems to full-featured document editors.

The extensive plugin ecosystem, combined with jQuery's ease of use, makes CKEditor a versatile choice for developers seeking to enhance their application's content creation capabilities. By following the guidelines and examples in this article, you'll be able to implement a robust editing solution that meets your specific needs while providing an excellent user experience.

Start enhancing your application's user experience by adding CKEditor today and giving your users the power to create rich, formatted content with ease!

Happy coding! ✨

Topics Covered

About Author

I'm Maulik Paghdal, the founder of Script Binary and a passionate full-stack web developer. I have a strong foundation in both frontend and backend development, specializing in building dynamic, responsive web applications using Laravel, Vue.js, and React.js. With expertise in Tailwind CSS and Bootstrap, I focus on creating clean, efficient, and scalable solutions that enhance user experiences and optimize performance.