Create custom style dropdowns on Quill

I’m putting this one up quickly so the info is out there. If you come across this and need more info, just comment on the post.

Set up the editor:

      // Create editor
      this.editor = new Quill('#' + this.id, {
        modules: {
          toolbar: {
            container: [
              [{'customStyles': this.styleList}],
              [{'align': []}],
              ['bold', 'italic', 'underline', 'strike'],
              [{'list': 'ordered'}, {'list': 'bullet'}],
              [{'color': []}, {'background': []}],
              ['blockquote', 'code-block'],
              [{'indent': '-1'}, {'indent': '+1'}],
              ['clean']
            ],
            handlers: {
              'customStyles': function (index) {
                vm.applyCustomStyle(index)
              }
            }
          }
        },
        theme: 'snow'
      })

      // Add custom style dropdown
      const dropdownPickerItems = Array.prototype.slice.call(document.querySelectorAll('.ql-customStyles .ql-picker-item'))
      dropdownPickerItems.forEach(function (item) {
        item.textContent = vm.customStyles[item.dataset.value]['name']
      })
      document.querySelector('.ql-customStyles .ql-picker-label').innerHTML = 'Styles' + document.querySelector('.ql-customStyles .ql-picker-label').innerHTML

Inject the styles:

      injectStyles () {
        let Block = Quill.import('blots/block')
        let css = ''

        // Register all custom styles
        for (let i = 0; i < this.customStyles.length; i++) {
          let className = this.customStyles[i]['class']
          let element = this.customStyles[i]['element']
          let style = this.customStyles[i]['style']

          // Set up Quill Blot
          class Blot extends Block {
            static create () {
              let node = super.create()
              if (className) {
                node.setAttribute('class', className)
              }
              return node
            }
          }

          Blot.blotName = this.stylePrefix + i
          Blot.tagName = element
          Quill.register(Blot)

          // Create style list for dropdown
          this.styleList.push(i)

          // Create CSS
          let name = (className) ? element + '.' + className : element
          css += '#' + this.id + ' ' + name + '{' + style + '}\n'
        } // Next i

        // Set master CSS
        this.customCSS = css
      },
      applyCustomStyle (index) {
        if (!index) { index = '0' }
        this.editor.format(this.stylePrefix + index, true)
      }

 

Leave a Reply

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