Home
NOTE: I'm in the middle of upgrading the site. Most things are in place, but some things are missing and/or broken. This includes alt text for images. Please bear with me while I get things fixed.

Code Block Web Component With Copy Button

This is a prototype to start making a code block web component that has a button to automatically copy the code. It's working, but I need to play around with it some more to put it through it's paces. Another thing to add is a timer to revert the text back from "Copied!" to "Copy" after a short wait.


this is where
the blocks
will go
  

JavaScript

customElements.define('code-block-example', 
  class extends HTMLElement {    
    constructor() {
      super()
      this.attachShadow({ mode: 'open' })
    }

    addClickListener() {
      const el = this.shadowRoot.querySelector('button')
      el.addEventListener('click', () => this.copyCode())
    }

    connectedCallback() {
      const sr = this.shadowRoot
      const template = this.makeTemplate()
      sr.appendChild(template.content.cloneNode(true))
      sr.querySelector('#code-output').innerHTML = 
        this.querySelector('code').innerHTML
      this.addClickListener()
    }

    async copyCode() {
      const button = this.shadowRoot.querySelector('button')
      try {
        await navigator.clipboard.writeText(
          this.querySelector('code').innerText
        )
        button.innerHTML = "Copied!"
      } catch (err) {
        button.innerHTML = "Error copying"
      }
    } 

    makeTemplate() {
      const t = this.ownerDocument.createElement('template') 
      t.innerHTML = `
<style>
.code-wrapper {
  position: relative;
}
.copy-button {
  position: absolute;
  right: 0;
}
</style>
<div class="code-wrapper">
  <button class="copy-button">Copy</button>
  <pre><code id="code-output"></code></pre>
</div>`
      return t
    }
  }
)
~ fin ~