TheRogerLAB Codes

Share button web component

  June, 2021

Introduction

This component consists in a share social media button. Let's start by creating the structure of our web component. Create a file shareLab.js:

class shareLab extends HTMLElement {

  //Here will be all the functionality.

}
window.customElements.define('share-lab', shareLab);

Step 1: Add a constructor and getters

class shareLab extends HTMLElement {
  constructor () {
    super();
  }
  get url() {
    return this.hasAttribute('url');
  }
  get urlPic() {
    return this.hasAttribute('urlPic');
  }
  get type() {
    return this.hasAttribute('type');
  }
}
window.customElements.define('share-lab', shareLab);

In this case we create three attributes:

Step 2: Add a function connectedCallback

It fires when the component is created

class shareLab extends HTMLElement {
  //Step 1

  connectedCallback () {

    //Here will be the functionality.

  }
}
window.customElements.define('share-lab', shareLab);

Inside connectedCallback function we will create two things:

Filling the connectedCallback function:

class shareLab extends HTMLElement {
  //Step 1

  connectedCallback () {
    let shadowRoot = this.attachShadow({mode: 'open'});
    shadowRoot.innerHTML = `
    <style>
      a{text-decoration:none;color:none;}
    </style>
    <a id='share_btn_container' target="_blank">
      <slot></slot>
    </a>
    `;

    if(this.type && this.url){
      if(this.getAttribute('type') == 'facebook'){
        shadowRoot.querySelector('#share_btn_container').setAttribute('href','http://www.facebook.com/sharer.php?u='+this.getAttribute('url'));
      }
      if(this.getAttribute('type') == 'twitter'){
        shadowRoot.querySelector('#share_btn_container').setAttribute('href','https://twitter.com/intent/tweet?text='+this.getAttribute('url'));
      }
      if(this.getAttribute('type') == 'whatsapp'){
        shadowRoot.querySelector('#share_btn_container').setAttribute('href','whatsapp://send?text='+this.getAttribute('url'));
      }
      if(this.getAttribute('type') == 'pinterest'){
        shadowRoot.querySelector('#share_btn_container').setAttribute('href','http://www.pinterest.com/pin/create/button/?media='+this.getAttribute('urlPic')+'&url='+this.getAttribute('url'));
      }
    }
  }
}
window.customElements.define('share-lab', shareLab);

Check a working demo for this code:

SEE DEMO RATE THIS ARTICLE
4.5
27
TheRogerLAB Codes
Powered by TheRogerLAB Sandbox

info@therogerlab.com