Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!-- begin snippet: js hide: false console: true babel: false -->
- <!-- language: lang-js -->
- var mutationConfiguration = {
- attributes: true,
- childList: true
- };
- if (document.readyState === "complete") onLoad();
- else addEventListener("load", onLoad);
- var managingDoms = [];
- function onLoad() {
- document.querySelectorAll("label[for]").forEach(manageLabel);
- if (typeof MutationObserver === "function") {
- var observer = new MutationObserver(function(list) {
- list.forEach(function(item) {
- ({
- "attributes": function() {
- // if attributeName is supported it is a HTMLElement.
- if (item.attributeName === "for") manageLabel(item.target);
- },
- "childList": function() {
- item.addedNodes.forEach((newNode) =>{
- if (newNode instanceof HTMLLabelElement && newNode.hasAttribute("for")) manageLabel(newNode);
- });
- }
- }[item.type])();
- });
- });
- observer.observe(document.body, mutationConfiguration);
- }
- }
- function manageLabel(label) {
- if (managingDoms.includes(label)) return;
- label.addEventListener("click", onLabelClick);
- managingDoms.push(label);
- }
- function onLabelClick(event) {
- if (event.defaultPrevented) return;
- var id = this.getAttribute("for");
- var target = document.getElementById(id);
- if (target !== null) { // null comparison better than instanceof for speed
- this.removeAttribute("for");
- target.click();
- target.focus();
- setTimeout(()=>{
- this.setAttribute("for", id);
- }, 0);
- }
- }
- <!-- language: lang-css -->
- label {
- -webkit-user-select: none;
- -moz-user-select: none;
- -ms-user-select: none;
- user-select: none;
- padding: 10px;
- border: 1px solid black;
- cursor: pointer;
- }
- <!-- language: lang-html -->
- <input type="checkbox" id="a">
- <input type="text" id="b">
- <label for="a">A</label>
- <script>
- setTimeout(function() {
- var label = document.createElement("label");
- label.setAttribute("for", "b");
- label.textContent = "b";
- document.body.appendChild(label);
- }, 3E3);
- </script>
- <!-- end snippet -->
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement