Last active
September 24, 2020 13:59
-
-
Save mgalante/0bea49b2c830f27a6af72e4abf9993f3 to your computer and use it in GitHub Desktop.
Custom Element Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!DOCTYPE html> | |
| <html> | |
| <head> | |
| <meta charset="utf-8"> | |
| <meta name="viewport" content="width=device-width"> | |
| <title>JS Bin</title> | |
| </head> | |
| <body> | |
| <div>Hola qwe qwe | |
| <p is="word-count"></p></div> | |
| <script> | |
| class WordCount extends HTMLParagraphElement { | |
| constructor() { | |
| // Always call super first in constructor | |
| super(); | |
| // count words in element's parent element | |
| var wcParent = this.parentNode; | |
| function countWords(node){ | |
| var text = node.innerText || node.textContent | |
| return text.split(/\s+/g).length; | |
| } | |
| // Create a shadow root | |
| var shadow = this.attachShadow({mode: 'open'}); | |
| // Create text node and add word count to it | |
| var text = document.createElement('span'); | |
| text.textContent = 'Words: ' + countWords(wcParent);; | |
| // Append it to the shadow root | |
| shadow.appendChild(text); | |
| // Update count when element content changes | |
| setInterval(function() { | |
| var count = 'Words: ' + countWords(wcParent); | |
| text.textContent = count; | |
| }, 200) | |
| } | |
| } | |
| // Define the new element | |
| customElements.define('word-count', WordCount, { extends: 'p' }); | |
| </script> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment