I have created a simple package for collapsible elements with an option to close the element when clicked outside of it with an attribute data-close-on-click-outside
. Locally it works, and also if I were to copy the JS into JSFiddle it works, but when I include the JS from a CDN, the event listener does not seem to be triggered. An example can be seen in this JSFiddle . Why does my code not work when included as a resource from a CDN in JSFiddle?
nb: I do not think there is something wrong with my code, as it works everywhere except on JSFiddle (minified or not), but for completeness here is my code:
HTML
<button data-collapsible-target="collapsible-close">Toggle me</button>
<div class="collapsible-close" data-close-on-click-outside>
This *should* close when clicked outside...
</div>
JS
document.addEventListener('click', (event) => {
const element = event.target;
const targetSelector = element.getAttribute('data-collapsible-target');
if (targetSelector !== null) {
toggleCollapse(targetSelector);
}
}, false);
const toggleCollapse = targetSelector => {
const targets = document.querySelectorAll('.' + targetSelector);
targets.forEach(target => {
if (!target.classList.contains('collapsible-show')) {
target.style.maxHeight = target.scrollHeight + 'px';
} else {
target.style.maxHeight = 0 + 'px';
}
target.classList.toggle('collapsible-show');
});
}
const closeOnClickOutsideElements = document.querySelectorAll('[data-close-on-click-outside]');
closeOnClickOutsideElements.forEach(element => hideOnClickOutside(element))
function hideOnClickOutside(element) {
const outsideClickListener = event => {
// Third checks if the element clicked isn't the toggler, which would result in a double click event that conflict each other.
if (!element.contains(event.target) && isVisible(element) && !element.classList.contains(event.target.getAttribute('data-collapsible-target'))) {
element.classList.remove('collapsible-show')
element.style.maxHeight = 0;
}
}
document.addEventListener('click', outsideClickListener)
const isVisible = elem => !!elem && !!(elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length) // source (2018-03-11): https://github.com/jquery/jquery/blob/master/src/css/hiddenVisibleSelectors.js
}
Edit: figured it out, see answer below.
JSFiddle loads the resource in the <head>
of the file. This resource works if it is added at the end of the <body>
, before the closing tag </body>
. I could change the script by wrapping it in document.addEventListener("DOMContentLoaded", function() {});
if I wanted to be able to use in when it is included in the <head>
of the document.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.