const sidenotes = (function () { // Private variable to store media query const mediaQuery = window.matchMedia('(min-width: 600px)'); // Event listener functions function onPageLoad() { console.log('Page loaded'); createSidenotes(); } function onResize() { console.log('Window resized'); positionSidenotes(); } function onMediaQueryChange(e) { if (e.matches) { console.log('Media query matched (min-width: 600px)'); } else { console.log('Media query did not match (min-width: 600px)'); } positionSidenotes(); } // Function to create sidenotes function createSidenotes() { const footnoteLinks = document.querySelectorAll('[data-footnote-ref]'); const footnotesSection = document.querySelector('[data-footnotes]'); if (!footnotesSection) { console.warn('Footnotes section not found'); return; } let previousBottom = 0; footnoteLinks.forEach((link, index) => { const footnoteId = link.getAttribute('href').substring(1); const footnoteElement = footnotesSection.querySelector(`#${footnoteId}`); const footnoteIndexMatch = footnoteId.match(/fn-(.+)/); const footnoteIndex = footnoteIndexMatch ? footnoteIndexMatch[1] : 'unknown'; if (footnoteElement) { const sidenote = document.createElement('div'); sidenote.className = 'sidenote'; sidenote.innerHTML = `${footnoteIndex}` sidenote.innerHTML += footnoteElement.innerHTML; document.body.appendChild(sidenote); positionSidenote(link, sidenote, previousBottom); previousBottom = window.scrollY + sidenote.getBoundingClientRect().bottom + 10; } else { console.warn(`Footnote with ID ${footnoteId} not found`); } }); } // Function to position sidenotes function positionSidenotes() { const footnoteLinks = document.querySelectorAll('[data-footnote-ref]'); const sidenotes = document.querySelectorAll('.sidenote'); let previousBottom = 0; footnoteLinks.forEach((link, index) => { const sidenote = sidenotes[index]; if (sidenote) { positionSidenote(link, sidenote, previousBottom); previousBottom = window.scrollY + sidenote.getBoundingClientRect().bottom + 10; } }); } // Function to position a single sidenote function positionSidenote(link, sidenote, previousBottom) { const article = document.querySelector('article'); const articleRect = article.getBoundingClientRect(); const linkRect = link.getBoundingClientRect(); const topPosition = Math.max(window.scrollY + linkRect.top, previousBottom); sidenote.style.position = 'absolute'; sidenote.style.top = `${topPosition}px`; sidenote.style.left = `${window.scrollX + articleRect.right + 10}px`; } // Public API return { init: function () { // Page load event listener window.addEventListener('DOMContentLoaded', onPageLoad); // Window resize event listener window.addEventListener('resize', onResize); // Media query change event listener mediaQuery.addListener(onMediaQueryChange); }, }; })(); // Initialize the module sidenotes.init();