(() => { const breakpoint = window.matchMedia('(max-width: 991px)'); const originalPositions = new Map(); function getTargetModule(index) { return document.getElementById(`right-${index}`); } function moveElements(isMobile) { document.querySelectorAll('[id^="left-"]').forEach(el => { const match = el.id.match(/left-(\d+)/); if (!match) return; const index = match[1]; // save original position only once if (!originalPositions.has(el)) { originalPositions.set(el, { parent: el.parentNode, nextSibling: el.nextSibling }); } if (isMobile) { const target = getTargetModule(index); if (target && el.parentNode !== target) { target.appendChild(el); } } else { const original = originalPositions.get(el); if (!original) return; if (original.nextSibling) { original.parent.insertBefore(el, original.nextSibling); } else { original.parent.appendChild(el); } } }); } // initial execution moveElements(breakpoint.matches); // listen for breakpoint changes breakpoint.addEventListener('change', e => { moveElements(e.matches); }); })();