Home » Javascript » Cannot Get Custom Dropdown to Work in QuillJS Editor

Cannot Get Custom Dropdown to Work in QuillJS Editor

Posted by: admin November 1, 2017 Leave a comment

Questions:

Description: I’m having trouble creating a dropdown in the Quill Editor toolbar. Any help would be appreciated. Ideally, I want the dropdown to show up in the toolbar and add the select option text as text in the editor.

Test Case: https://codepen.io/Graphettion/pen/OxezbO

HTML

<div id="editor-toolbar">
  <select class="ql-emailVars">
    <option value="1">Account Url</option>
    <option value="2">First Name</option>
    <option value="3">Login</option>
    <option value="4">Org Name</option>
    <option value="5">Support Email</option>
  </select>
</div>
<div id="editor"></div>
<div class="text-output"></div>
<div class="html-output"></div>

JS

const quill = new Quill('#editor', {
  modules: {
    toolbar: {
      container: "#editor-toolbar",
        handlers: {
          "emailVars": emailVars
        }
    }
  },
  theme: 'snow'
});

// Add Custom Dropdown to Toolbar
function emailVars(args) {
  const value = args[0];
  const cursorPosition = this.quill.getSelection().index
  this.quill.insertText(cursorPosition, value)
  this.quill.setSelection(cursorPosition + value.length)
}

Thank you,

Answers:

I had to add some CSS to display it on the toolbar and some JS to insert it to the text editor.

CSS

.ql-picker.ql-emailVars {
  width: 120px;
}

.ql-picker.ql-emailVars .ql-picker-item::before, 
.ql-picker.ql-emailVars .ql-picker-label::before {
  content: 'Custom'
}

.ql-picker.ql-emailVars [data-value="1"]::before {
  content: 'Account Url'
}

.ql-picker.ql-emailVars [data-value="2"]::before {
  content: 'First Name'
}

.ql-picker.ql-emailVars [data-value="3"]::before {
  content: 'Login'
}

.ql-picker.ql-emailVars [data-value="4"]::before {
  content: 'Org Name'
}

.ql-picker.ql-emailVars [data-value="5"]::before {
  content: 'Support Email'
}

JS

const quill = new Quill('#editor', {
  modules: {
    toolbar: {
      container: "#editor-toolbar",
      handlers: {
        "emailVars": emailVars
      }
    }
  },
  theme: 'snow'
});

// Add Custom Dropdown to Toolbar
function emailVars(args) {
  const value = args[0]
  const cursorPosition = this.quill.getSelection().index
  if (value == 1) {
    this.quill.insertText(cursorPosition, "{AccountURL}")
  } else if (value == 2) {
    this.quill.insertText(cursorPosition, "{FirstName}")
  } else if (value == 3) {
    this.quill.insertText(cursorPosition, "{Login}")
  } else if (value == 4) {
    this.quill.insertText(cursorPosition, "{OrganizationName}")
  } else if (value == 5) {
    this.quill.insertText(cursorPosition, "{SupportEmail}")
  } else {
    this.quill.insertText(cursorPosition, "Please add an email variable.")
  }

  this.quill.setSelection(cursorPosition + value.length)
}

https://codepen.io/Graphettion/pen/OxezbO