Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel is required to process package imports. If you need a different preprocessor remove all packages first.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Demo Web Component</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/webcomponentsjs/2.4.3/custom-elements-es5-adapter.js"></script>
</head>
<body>
  <user-details-card api-url="https://reqres.in/api/users/1"></user-details-card>
  <script>
   //# sourceURL=pen.js
  </script>
</body>
</html>
              
            
!

CSS

              
                
              
            
!

JS

              
                // créer une class qui extend HTMLElement
class UserDetailsCard extends HTMLElement {
  
  constructor() {
    super();
    // Ajouter un click listener sur notre component
    this.addEventListener('click', e => {
      this.toggleDetails();
    });
  }

  connectedCallback() {
    // get current scoop context
    this.currentDocument = document.currentScript.ownerDocument;
    // Création d'une racine fantôme
    const shadowRoot = this.attachShadow({mode: 'open'});
    // creation du template de base avec une class css pour l'identifié par la suite
    const template = this.currentDocument.createElement('div');
    template.setAttribute('class', 'card__preview');
    // on genere une instance uniqu
    const instance = template.cloneNode(true);
    // et on l'ajout au ShadowDom
    shadowRoot.appendChild(instance);
    // pour finir on peu charger les info user
    this.loadUserData();
  }

  async loadUserData() {
    // on check si l'attribut `api-url` à bien été renseigné
    if(!this.hasAttribute('api-url')) 
      throw new Error('Vous devez implementer le paramettre `api-url` pour faire fonctionner ce component');
    // si oui on récupère l'url et on lance la requête
    const apiUrl = this.getAttribute('api-url');
    // request api to get data
    const {data: user} = await fetch(apiUrl)
      .then(res => res.json())
      .catch((error) => {
          console.error(error);
      });
    // pui on update de ShadowDOM
    this.render(user);
  }

  render(user) {
    // on identifi l'element html à modifier
    const card__preview = this.shadowRoot.querySelector('.card__preview');
    // on ajoute de cpntenu HTML avec les info en provenance de l'api
    card__preview.insertAdjacentHTML('afterbegin', `
      <img class=card__img" src="${user.avatar}">
      <p class="card__details">
        ${user.email}<br/>
        ${user.first_name} ${user.last_name}
      </p>
    `);
    // on cache le details content
    const card__details = this.shadowRoot.querySelector('.card__details');
    card__details.style.display = 'none';
  }

  toggleDetails() {
    // on identifi la zone à traiter
    const card__details = this.shadowRoot.querySelector('.card__details');
    // get current display mode
    const display = card__details.style.display;
    // switch display mode
    if (display === 'none') {
      card__details.style.display = 'block';
    } else {
      card__details.style.display = 'none';
    }
  }

}

customElements.define('user-details-card', UserDetailsCard);
              
            
!
999px

Console