Guest User

Untitled

a guest
Nov 14th, 2018
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.16 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1">
  6. <title>Web Component</title>
  7. <script type="text/javascript">
  8. // We define an ES6 class that extends HTMLElement
  9. class CounterElement extends HTMLElement{
  10. constructor() {
  11. super();
  12. // Initialise the counter value
  13. this.counter = 0;
  14.  
  15. // We attach an open shadow root to the custom element
  16. const shadowRoot= this.attachShadow({mode: 'open'});
  17.  
  18. // We define some inline styles using a template string
  19. const styles=`
  20. :host {
  21. position: relative;
  22. font-family: sans-serif;
  23. }
  24.  
  25. #counter-increment, #counter-decrement {
  26. width: 60px;
  27. height: 30px;
  28. margin: 20px;
  29. background: none;
  30. border: 1px solid black;
  31. }
  32.  
  33. #counter-value {
  34. font-weight: bold;
  35. }
  36. `;
  37.  
  38. // We provide the shadow root with some HTML
  39. shadowRoot.innerHTML = `
  40. <style>${styles}</style>
  41. <h3>Counter</h3>
  42. <slot name='counter-content'>Button</slot>
  43. <button id='counter-increment'> - </button>
  44. <span id='counter-value'> 0 </span>
  45. <button id='counter-decrement'> + </button>
  46. `;
  47.  
  48. // We can query the shadow root for internal elements
  49. // in this case the button
  50. this.incrementButton = this.shadowRoot.querySelector('#counter-increment');
  51. this.decrementButton = this.shadowRoot.querySelector('#counter-decrement');
  52. this.counterValue = this.shadowRoot.querySelector('#counter-value');
  53.  
  54. // We can bind an event which references one of the class methods
  55. this.incrementButton.addEventListener("click", this.decrement.bind(this));
  56. this.decrementButton.addEventListener("click", this.increment.bind(this));
  57.  
  58. }
  59. increment() {
  60. this.counter++
  61. this.invalidate();
  62. }
  63. decrement() {
  64. this.counter--
  65. this.invalidate();
  66. }
  67. // Call when the counter changes value
  68. invalidate() {
  69. this.counterValue.innerHTML = this.counter;
  70. }
  71. }
  72. // This is where the actual element is defined for use in the DOM
  73. customElements.define('counter-element', CounterElement);
  74. </script>
  75. </head>
  76. <body>
  77. <counter-element></counter-element>
  78. </body>
  79. </html>
Add Comment
Please, Sign In to add comment