Search code examples
javascriptjquerydjangocss-selectorsquill

Multiple focus selectors to dinamically show QuillJS toolbar, is it possible?


I'm using Django's QuillJS version, and what I'm trying to do is display the toolbar of the selected text area only. Using JS it kinda worked:

const parentDiv = Array.from(document.getElementsByClassName("django-quill-widget-container"));
const toolbar = Array.from(document.getElementsByClassName("ql-toolbar"));
const editor = Array.from(document.getElementsByClassName("ql-editor"));

for (let i = 0; i < editor.length; i++) {
    toolbar[i].style.display = "none";
    parentDiv[i].style.borderTop = "1px solid #ccc";
    editor[i].addEventListener("focusin", function () {
      toolbar[i].style.display = "";
      parentDiv[i].style.borderTop = "";
    });
    editor[i].addEventListener("focusout", function () {
      toolbar[i].style.display = "none";
      parentDiv[i].style.borderTop = "1px solid #ccc";
    });
}

The problem is that clicking the toolbar to utilize its features also counts as focusout.

So yeah, it doesn't work.

Any idea?


Solution

  • In the end I used a more simplistic approach:

    const parentDiv = Array.from(document.getElementsByClassName("django-quill-widget-container"));
    const toolbar = Array.from(document.getElementsByClassName("ql-toolbar"));
    const editor = Array.from(document.getElementsByClassName("ql-editor"));
    
    
    function clearToolbar(index) {
      toolbar[index].style.display = "none";
      parentDiv[index].style.borderTop = "1px solid #ccc";
    }
    
    let editorArray = [0,1,2,3,4,5];
    
    for (let i = 0; i < editor.length; i++) {
      toolbar[i].style.display = "none";
      parentDiv[i].style.borderTop = "1px solid #ccc";
      editor[i].addEventListener("focusin", function () {
        Array.prototype.except = function(val) {
          return this.filter(function(x) { return x !== val; });
        };
    
        parentDiv[i].style.borderTop = "";
        toolbar[i].style.display = "";
        editorArray.except(i).forEach(clearToolbar);
      });
    }
    

    It filters an array that contains the TextInputs indexes, excluding the index of the selected Text Field, and apply the styles I need. Without the focusout listener the toolbar now works perfectly.