repl.it
@todojs/

05-random-lorem-ipsum-count-words

HTML, CSS, JS

No description

fork
loading
Files
  • index.html
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Light DOM</title>
  <script src="https://unpkg.com/@webcomponents/webcomponentsjs/webcomponents-loader.js"></script>
</head>
<body>
<button id="getText">Random Lorem Ipsum</button>
<wc-words></wc-words>
<script>
  document.querySelector ('#getText').addEventListener ('click', function () {
    const words      = parseInt (Math.random () * 200);
    const paragraphs = parseInt (words / 20);
    fetch ('https://www.randomtext.me/api/lorem/p-' + paragraphs + '/1-' + words)
      .then (function (response) {
        if (response.status === 200) {
          return response.json ();
        }
      }).then (function (data) {
      document.querySelector ('wc-words').innerHTML = data.text_out;
    });
  });

  customElements.define ('wc-words', class extends HTMLElement {
    constructor () {
      super ();
      this.attachShadow ({mode : 'open'});
      this.shadowRoot.innerHTML = '<h3>0 words</h3>';
    }
    connectedCallback () {
      new MutationObserver (
        this.count.bind (this)
      ).observe (
        this,
        {attributes : true, childList : true, characterData : true}
      );
    }
    count () {
      const texts = [...this.querySelectorAll ('p')]
        .map ((p) => p.innerText);
      const count = texts
        .join (' ')
        .replace (/[.!?\\-]|\s|\n|\r/gi, " ")
        .replace (/[ ]{2,}/gi, " ")
        .split (' ')
        .filter (function (str) {
          return str.trim () !== ""
        })
        .length;
      this.shadowRoot.innerHTML = '<h3>' + count + ' words</h3>' + this.innerHTML;
    }

  });
</script>
</body>
</html>
result
console
?