mdBook
mdBook copied to clipboard
Autoexpanding of <details></details> before printing
Problem
From time to time I'm using html details
-tags to hide not-so-interesting parts from the initial visibility. But, when printing (to a pdf), it would make sense to expand all those blocks, as in a pdf, those links are not renderd to a clickable link/button. To my (very limited) knowledge, this would be e.g. possible with Javascript (see here).
Proposed Solution
Include Javascript to expand all expandable sections before printing (for media:print) and restore their previous state afterwords.
Notes
No response
Ok, I just tested this via additional-js
and it works:
// open closed details elements for printing
window.addEventListener('beforeprint',() =>
{
const allDetails = document.body.querySelectorAll('details');
for(let i=0; i<allDetails.length; i++)
{
if(allDetails[i].open)
{
allDetails[i].dataset.open = '1';
}
else
{
allDetails[i].setAttribute('open', '');
}
}
});
// after printing close details elements not opened before
window.addEventListener('afterprint',() =>
{
const allDetails = document.body.querySelectorAll('details');
for(let i=0; i<allDetails.length; i++)
{
if(allDetails[i].dataset.open)
{
allDetails[i].dataset.open = '';
}
else
{
allDetails[i].removeAttribute('open');
}
}
});