Advertisement
Kawiesh

Shadow DOM Template

Nov 26th, 2021 (edited)
1,264
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. let create= (x)=> document.createElement(x),
  2. select= (x,y=document)=> y.querySelector(x),
  3. selectAll= (x,y=document)=> y.querySelectorAll(x);
  4.  
  5. let template= create("template");
  6. template.innerHTML=`<style>
  7. *{
  8. box-sizing:border-box;
  9. margin:0; padding:0;
  10. outline:none;
  11. pointer-events: auto;
  12. }
  13.  
  14. #container{
  15. z-index:99999;
  16. position: absolute;
  17. left:20px; top:20px;
  18. display:flex;
  19. flex-direction:column;
  20. pointer-events: none;
  21. }
  22.  
  23. path{
  24. stroke:red;
  25. stroke-width:5px;
  26. }
  27.    
  28. .close{
  29. position:absolute;
  30. top:-20px; left: 0;
  31. width:20px; height:20px;
  32. border:1px solid red;
  33. cursor: pointer;
  34. }
  35.  
  36. 🔴
  37.  
  38. </style>
  39. <div id="container">
  40. <svg class="close" viewbox="0 0 40 40"><path d="M 10,10 L 30,30 M 30,10 L 10,30"/></svg>
  41. 🔴
  42. </div>`;
  43.  
  44. let name= "🔴-🔴"
  45. if (!customElements.get(name)){
  46. window.customElements.define(name,
  47. class extends HTMLElement{
  48. constructor(){
  49. super();
  50. this.attachShadow({mode:"open"});              
  51. }          
  52. })
  53. }
  54.  
  55. //--------------------------------------------
  56. let a= create(name), b= select(name);
  57. a.shadowRoot.append(template.content.cloneNode(true));
  58.  
  59. if(b){
  60. b.remove();
  61. document.body.append(a);
  62. }
  63. else document.body.append(a);
  64.  
  65. let container= select("#container", a.shadowRoot),
  66. all= selectAll("#container>*", a.shadowRoot),
  67. close= select(".close", a.shadowRoot);
  68.  
  69.  
  70. let hide= true;
  71. close.onclick= function(){
  72. all.forEach(i=> i.style.display= hide ? "none" : "block");
  73. this.style.display= "block";
  74. hide= !hide;
  75. };
  76.  
  77. function drag(e){
  78. e.preventDefault();
  79. let touchLocation = e.targetTouches[0];
  80. let x= touchLocation.pageX || e.pageX;
  81. let y= touchLocation.pageY || e.pageY;
  82.  
  83. container.style.left= x + "px";
  84. container.style.top= y + "px";
  85. };
  86.  
  87. close.ontouchmove= drag;
  88. close.onmousemove= drag;
  89. close.ondblclick=()=> a.remove();
  90.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement