Search code examples
javascriptrich-text-editorquill

How to create own format buttons in Quill.js?


I just started playing with Quill.js rich text editor and ran into a challenge while trying to create my own text formatting buttons.

In HTML I added the following radio buttons inside .​

<form name="temp-form">
<input type="radio" name="font-size-radio" value="10px">10px
<input type="radio" name="font-size-radio" value="13px">13px
</form>

In JavaScript I try to change font size settings using prepareFormat:

var radios = document.forms["temp-form"].elements["font-size-radio"];
for (radioValue in radios) {
  radios[radioValue].onclick = function() {
    editor.prepareFormat('size', this.value);​​
  }
}

After I click on radio buttons JavaScript gets to prepareFormat line, but when I continue typing in text editor text format stays the same.

For debugging I tried using ​prepareFormat('​bold', ​true) from Quill JS documentation example ​instead of ​prepareFormat('size', this.value), but that seems to be ignored too.

What would you recommend here?


Solution

  • The issue here is when the onclick handler is called, the editor no longer has focus, so there is no cursor to prepare formats for. So the only missing step is to add a focus() call before calling prepareFormat():

    var editor = new Quill('#editor');
    
    var radios = document.forms["temp-form"].elements["font-size-radio"];
    for (radioValue in radios) {
      radios[radioValue].onclick = function(e) {
        editor.focus();
        editor.prepareFormat('size', this.value)
      }
    }
    <script src="https://cdn.quilljs.com/0.20.1/quill.js"></script>
    
    <form name="temp-form">
    <input type="radio" name="font-size-radio" value="10px">10px
    <input type="radio" name="font-size-radio" value="13px">13px
    <input type="radio" name="font-size-radio" value="18px">18px
    </form>
    
    <div id='editor'>
    Test
    </div>