Advertisement
Guest User

Untitled

a guest
Nov 22nd, 2019
318
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.40 KB | None | 0 0
  1. <!-- begin snippet: js hide: false console: true babel: false -->
  2.  
  3. <!-- language: lang-js -->
  4.  
  5. var mutationConfiguration = {
  6. attributes: true,
  7. childList: true
  8. };
  9.  
  10. if (document.readyState === "complete") onLoad();
  11. else addEventListener("load", onLoad);
  12.  
  13. var managingDoms = [];
  14.  
  15. function onLoad() {
  16. document.querySelectorAll("label[for]").forEach(manageLabel);
  17. if (typeof MutationObserver === "function") {
  18. var observer = new MutationObserver(function(list) {
  19. list.forEach(function(item) {
  20. ({
  21. "attributes": function() {
  22. // if attributeName is supported it is a HTMLElement.
  23. if (item.attributeName === "for") manageLabel(item.target);
  24. },
  25. "childList": function() {
  26. item.addedNodes.forEach((newNode) =>{
  27. if (newNode instanceof HTMLLabelElement && newNode.hasAttribute("for")) manageLabel(newNode);
  28. });
  29. }
  30. }[item.type])();
  31. });
  32. });
  33. observer.observe(document.body, mutationConfiguration);
  34. }
  35. }
  36.  
  37. function manageLabel(label) {
  38. if (managingDoms.includes(label)) return;
  39. label.addEventListener("click", onLabelClick);
  40. managingDoms.push(label);
  41. }
  42.  
  43. function onLabelClick(event) {
  44. if (event.defaultPrevented) return;
  45. var id = this.getAttribute("for");
  46. var target = document.getElementById(id);
  47. if (target !== null) { // null comparison better than instanceof for speed
  48. this.removeAttribute("for");
  49. target.click();
  50. target.focus();
  51. setTimeout(()=>{
  52. this.setAttribute("for", id);
  53. }, 0);
  54. }
  55. }
  56.  
  57. <!-- language: lang-css -->
  58.  
  59. label {
  60. -webkit-user-select: none;
  61. -moz-user-select: none;
  62. -ms-user-select: none;
  63. user-select: none;
  64. padding: 10px;
  65. border: 1px solid black;
  66. cursor: pointer;
  67. }
  68.  
  69. <!-- language: lang-html -->
  70.  
  71. <input type="checkbox" id="a">
  72. <input type="text" id="b">
  73. <label for="a">A</label>
  74. <script>
  75. setTimeout(function() {
  76. var label = document.createElement("label");
  77. label.setAttribute("for", "b");
  78. label.textContent = "b";
  79. document.body.appendChild(label);
  80. }, 3E3);
  81. </script>
  82.  
  83. <!-- end snippet -->
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement