Skip to content

Instantly share code, notes, and snippets.

@wojtekmaj
Last active January 24, 2020 11:16
Show Gist options
  • Save wojtekmaj/79bf3897ded7f356db43ebe74715c231 to your computer and use it in GitHub Desktop.
Save wojtekmaj/79bf3897ded7f356db43ebe74715c231 to your computer and use it in GitHub Desktop.
Polyfill for the HTML <details> element, with support for onToggle event
if (!('open' in document.createElement('details'))) {
const DETAILS = 'details';
const SUMMARY = 'summary';
function injectStyle(style) {
const styleElement = document.createElement('style');
styleElement.innerHTML = style;
document.getElementsByTagName('head')[0].appendChild(styleElement);
}
function createEvent(type) {
if (typeof Event === 'function') {
return new Event(type, { bubbles: true, cancelable: true });
}
const event = document.createEvent('Event');
event.initEvent(type, true, true);
return event;
}
function clickHandler(event) {
const { target } = event;
if (target.nodeName.toLowerCase() !== SUMMARY) {
return;
}
const details = target.parentNode;
if (!details) {
return;
}
if (details.getAttribute('open')) {
details.open = false;
details.removeAttribute('open');
} else {
details.open = true;
details.setAttribute('open', 'open');
}
const toggleEvent = createEvent('toggle');
details.dispatchEvent(toggleEvent);
}
window.addEventListener('click', clickHandler);
injectStyle(`
${DETAILS}, ${SUMMARY} { display: block; }
${DETAILS}:not([open]) > :not(${SUMMARY}) { display: none; }
${DETAILS} > ${SUMMARY}:before { content: "\u25b6"; display: inline-block; font-size: .8em; width: 1.5em; }
${DETAILS}[open] > ${SUMMARY}:before { content: "\u25bc"; }
`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment