jodit

How to create a custom button in Jodit to wrap the text in a code tag?


Basically I want to be able to generate html like <code>{a: true}</code>

As far as I can tell, the button should do the same thing as the "underline" button for example, except it will wrap the text in <code> instead of <u>;

I have tried using this:

{
    buttons:
      'bold,strikethrough,underline,italic,eraser,|,superscript,subscript,|,ul,ol,align,|,outdent,indent,|,font,fontsize,brush,paragraph,|,image,video,table,link,|,undo,redo,\n,selectall,cut,copy,paste,copyformat,|,hr,symbol,source,fullsize,print,code',

    language: lang,
    placeholder,
    toolbarAdaptive: false,
    uploader: {
      insertImageAsBase64URI: true,
    },
    controls: {
      code: {
        name: 'code',
        iconURL: 'someurl.com',
        tagRegExp: '_PxEgEr_/^(code)$/i',
        tags: ['code'],
        tooltip: 'Code',
      },
    },
  }

The button shows up in the toolbar, but nothing happens when I click it. The documentation shows buttons that insert text, but I need a button that wraps text instead.


Solution

  • Ok I figured it after going through their code, it's not well documented, but this is how you do it:

    {
      buttons: 'blockquote,code',
      controls: {
        code: {
          name: 'code',
          iconURL: 'someiconurl.com',
          tooltip: 'Insert Code Block',
          exec: function (editor) {
            editor.execCommand('formatBlock', false, 'code');
          },
          isActive: (editor, control) => {
            const current = editor.s.current();
            return Boolean(
              current && Jodit.modules.Dom.closest(current, 'code', editor.editor)
            );
          },
        },
        blockquote: {
          name: 'blockquote',
          iconURL: 'someiconurl.com',
          tooltip: 'Insert blockqoute',
          exec: function (editor) {
            editor.execCommand('formatBlock', false, 'blockquote');
          },
          isActive: (editor, control) => {
            const current = editor.s.current();
            return Boolean(
              current && Jodit.modules.Dom.closest(current, 'blockquote', editor.editor)
            );
          },
        },
      },
    }