Last active
July 19, 2024 08:19
-
-
Save rungta/ee5fbd5a780d804646fc52846e04643a to your computer and use it in GitHub Desktop.
Uncheck input[data-checkboxscope-input][type=checkbox] on a click outside [data-checkboxscope-container]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Uncheck any `input[type=checkbox]` (`[data-checkboxscope-input]`) | |
// outside a defined scope area (`[data-checkboxscope-container]`) | |
// | |
// Eg: | |
// | |
// <div data-checkboxscope-container> | |
// <input data-checkboxscope-input type=checkbox> | |
// </div> | |
// <div> | |
// <!-- a click here will uncheck the checkbox above --> | |
// </div> | |
(function (w) { | |
function closeScopedCheckboxes(checkbox_selector, scope_selector) { | |
return function (event) { | |
var el = event.target; | |
document | |
.querySelectorAll(scope_selector) | |
.forEach(function(toggleScope) { | |
if (!toggleScope.contains(el)) { | |
Array | |
.from(toggleScope.querySelectorAll(checkbox_selector)) | |
.filter(function (checkbox) { | |
return checkbox.checked && !(el instanceof HTMLLabelElement && checkbox == el.control); | |
}) | |
.map(function (checkbox) { | |
checkbox.click(); | |
}); | |
} | |
}); | |
}; | |
} | |
document.addEventListener('click', closeScopedCheckboxes('[data-checkboxscope-input]', '[data-checkboxscope-container]')); | |
document.addEventListener('touchend', closeScopedCheckboxes('[data-checkboxscope-input]', '[data-checkboxscope-container]')); | |
}(this)); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "checkboxscope", | |
"version": "0.2.0" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment