Vanilla JS Component

25-02-2023

class Description extends HTMLElement {

  constructor() {
    super();
    this.attachShadow({ mode: 'open' });
    this.render();
  }

  static get observedAttributes() {
    return ['title', 'description'];
  }

  attributeChangedCallback(name, oldValue, newValue) {
    if ((name === 'title' || name === 'description') && oldValue !== newValue) {
      this.render();
    }
  }

  render() {
    this.title = this.getAttribute('title');
    this.description = this.getAttribute('description');

    const template = document.createElement('template');
    template.innerHTML = `
      <style>
        .description-container {
          position: absolute;
          bottom: 1%;
          right: 1%;
          min-width: 200px;
          max-width: 500px;
          min-height: 100px;
          border-radius: 15px;
          z-index: 1;
          text-align: left;
          padding: 10px;
          background-color: black;
          color: white;
        }

        @media only screen and (max-width: 768px) {
          .description-container {
            left: 1%;
          }
        }
      </style>

      <div class="description-container">
        <span>${this.title}</span>
        <br>
        <br>
        <span>${this.description}</span>
      </div>
    `;

    // Clear the existing content and append the new template content to the shadow DOM
    this.shadowRoot.innerHTML = '';
    this.shadowRoot.appendChild(template.content.cloneNode(true));
  }
}

customElements.define('description-component', Description);