How do I implement Coloris npm package as a custom element?

Issue

I have been trying to implement an NPM called Coloris, to provide end-user color customization capability to a Wix website through a web component. From what I can see, the javascript isn’t working/executing. I’ve tried a few solutions for getting javascript to work in innerHTML, but they haven’t worked so far. This issue has stumped me for a week and I still can’t get the Coloris color picker to show/render. I can get as an HTML/IFrame embed, but need to make it work as a custom component

Below is the code for the web component. Any help/solutions would be greatly appreaciated


const createScript = () => {

const scriptElement = document.createElement('script');

scriptElement.src = "https://cdn.jsdelivr.net/gh/mdbassit/Coloris@latest/dist/coloris.min.js";

scriptElement.defer = true;

scriptElement.async = true;

return scriptElement;

}

const template = document.createElement('template');
template.innerHTML = `
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/mdbassit/Coloris@latest/dist/coloris.min.css"/>
<script src="https://cdn.jsdelivr.net/gh/mdbassit/Coloris@latest/dist/coloris.min.js"></script>
<input type="text" data-coloris>
`


class ColorisImp extends HTMLElement {
  
  connectedCallback() {

    this.attachShadow({mode: 'open'});
    this.appendChild(createScript());
    this.shadowRoot.appendChild(template.content.cloneNode(true));
   
  
  }
  

  
}

window.customElements.define('coloris-implement', ColorisImp);

Solution

I tested it, ColorIs does not work on DOM Elements inside shadowDOM

Your code can be made easier; to inject the <script> and <link> in the document.head

Note: ColorIs does not work properly in this SO snippet either;
here is a JSFiddle: https://jsfiddle.net/WebComponents/5j7h3ygw/

<script>
  window.customElements.define('color-is', class extends HTMLElement {
    connectedCallback() {
      const source = "//cdn.jsdelivr.net/gh/mdbassit/Coloris@latest/dist/";
      const create = (tag, props) =>
                      Object.assign(document.createElement(tag), props);
      document.head.append(
        create('script', {
          src: source + "coloris.min.js",
          defer: true,
          async: true
        }),
        create('link', {
          rel: "stylesheet",
          href: source + "coloris.min.css"
        })
      ); //append

      this.innerHTML = `<input type="text" data-coloris>`;

    }
  });
</script>

<color-is></color-is>

Answered By – Danny '365CSI' Engelman

Answer Checked By – Marilyn (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.