Quill: Add View source button – part 2


Part 1: Quill: Add View source button

Method 2:

Javascript

if (Quill.prototype.getHTML == undefined)
  Quill.prototype.getHTML = function() {
    return this.container.firstChild.innerHTML;
  };
  
if (Quill.prototype.pasteHTML == undefined)
  Quill.prototype.pasteHTML = function(html) {
    {
      this.container.firstChild.innerHTML = html;
    }
  }

Quill.prototype.showSource = function() {
  if (this.txtArea.style.display === "") {
    const html = this.txtArea.value;
    if (html === '<p><br/></p>') {
      this.html = null;
    } else {
      this.html = html.replace(new RegExp('<p><br/>', 'g'), '<p>')
    }
    this.pasteHTML(html);
  }
  this.txtArea.style.display =
    this.txtArea.style.display === "none" ? "" : "none";
}

Quill.ShowSource = function(t) {
  $(t).parents('.wyswyg')[0].quill.showSource()
}

$(function() {
  $(".wyswyg").each(function() {
    var e = $(this).find(".editor"),
      o = $(this).find(".toolbar");
    this.quill = new Quill(e.get(0), {
      theme: "snow",
      modules: {
        toolbar: o.get(0)
      }
    })

    this.quill.txtArea = document.createElement("textarea");
    this.quill.txtArea.style.cssText =
      "width: 100%;margin: 0px;background: rgb(29, 29, 29);box-sizing: border-box;color: rgb(204, 204, 204);font-size: 15px;outline: none;padding: 20px;line-height: 24px;font-family: Consolas, Menlo, Monaco, &quot;Courier New&quot;, monospace;position: absolute;top: 0;bottom: 0;border: none;display:none;resize: none;";

    var htmlEditor = this.quill.addContainer("ql-custom");
    htmlEditor.appendChild(this.quill.txtArea);

    this.quill.on("text-change", (delta, oldDelta, source) => {
      var html = this.quill.getHTML();
      this.quill.txtArea.value = html;
    });
    this.quill.txtArea.value = this.quill.getHTML();
  })

})

HTML:

<div class="wyswyg" id="ts">
  <div class="toolbar">
    <select class="ql-size">
    </select>
    <button class="ql-bold"></button>
    <button class="ql-italic"></button>
    <button class="ql-underline"></button>
    <button class="ql-strike"></button>
    <select title="Text Color" class="ql-color">
    </select>
    <select title="Background Color" class="ql-background">
    </select>
    <button class="ql-list" value="ordered"></button>
    <button class="ql-list" value="bullet"></button>
    <select title="Text Alignment" class="ql-align">
    </select>
    <button class="ql-link"></button>
    <button style="width: auto;" type="button" title="Source" class="btn btn-secondary btn-sm" onclick="Quill.ShowSource(this)">
      <i class="fa fa-code"></i> Source </button>
  </div>
  <div class="editor">www.tutorialspots.com</div>
</div>

Online demo for Quill v2: https://jsfiddle.net/sans_amour/9d6jxeut/

1 Comment

Leave a Reply