Advertisement
Guest User

HTMX + Webcomponents 2 levels

a guest
Dec 1st, 2024
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. //index.html
  2. <!DOCTYPE html>
  3. <html lang="en">
  4.  
  5. <head>
  6. <meta charset="UTF-8">
  7. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  8. <script type="module">
  9. import "./main.js";
  10. </script>
  11. <script src="https://unpkg.com/[email protected]"
  12. integrity="sha384-0895/pl2MU10Hqc6jd4RvrthNlDiE9U1tWmX7WRESftEDRosgxNsQG/Ze9YMRzHq"
  13. crossorigin="anonymous"></script>
  14. <title>Document</title>
  15. </head>
  16.  
  17. <body onload="test()">
  18. <main>
  19.  
  20. </main>
  21. </body>
  22.  
  23. </html>
  24.  
  25. //main.js
  26. import Component1 from './component_1.js';
  27.  
  28. window.test = () => {
  29. const main = document.querySelector('main');
  30. main.appendChild(new Component1());
  31. }
  32.  
  33. //component_1.js
  34. import Component2 from './component_2.js';
  35.  
  36. export default class Component1 extends HTMLElement {
  37. constructor() {
  38. super();
  39. }
  40.  
  41. connectedCallback() {
  42. const shadow = this.attachShadow({ mode: 'open' });
  43.  
  44. const h1 = document.createElement('h1');
  45. h1.textContent = 'Level 1';
  46. shadow.appendChild(h1);
  47.  
  48. const button = document.createElement('button');
  49. button.textContent = 'Level 1';
  50. button.setAttribute('hx-get', '/test');
  51. shadow.appendChild(button);
  52.  
  53. const level2 = new Component2();
  54. shadow.appendChild(level2);
  55.  
  56. htmx.process(shadow);
  57. }
  58. }
  59. customElements.define('component-1', Component1);
  60.  
  61. //component_2.js
  62. export default class Component2 extends HTMLElement {
  63. constructor() {
  64. super();
  65. }
  66.  
  67. connectedCallback() {
  68. const shadow = this.attachShadow({ mode: 'open' });
  69.  
  70. const h1 = document.createElement('h1');
  71. h1.textContent = 'Level 2';
  72. shadow.appendChild(h1);
  73.  
  74. const button = document.createElement('button');
  75. button.textContent = 'Level 2';
  76. button.setAttribute('hx-get', '/test');
  77. shadow.appendChild(button);
  78.  
  79. htmx.process(shadow);
  80. }
  81. }
  82. customElements.define('component-2', Component2);
  83.  
  84. //test
  85. Potato
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement