Hi!
I have this script, which rearranges DOM elements on a site in response to changing resolution basically creating a mobile version with different order of elements.
// repositionHighwaySelectorForMobile
const highwaySection = document.querySelector(".highway");
const highwayTitle = document.querySelector(".highway__title");
const highwayPicSelector = document.querySelector(
".highway__slider-buttons-container"
);
const mobileTitleAndSelectorWrapper = document.createElement("div");
const highwayMobileLine = document.querySelector(".highway__mobile-line");
const highwayArrowLeftContainer = document.querySelector(
".highway__slider-button-left"
);
const highwayArrowRightContainer = document.querySelector(
".highway__slider-button-right"
);
function repositionHighwaySelectorForMobile() {
if (breakPoint.matches) {
mobileTitleAndSelectorWrapper.classList.add(
"highway__title-and-selector-wrapper"
);
highwayMobileLine.after(highwayTitle);
highwayTitle.after(mobileTitleAndSelectorWrapper);
mobileTitleAndSelectorWrapper.appendChild(highwayTitle);
mobileTitleAndSelectorWrapper.appendChild(highwayPicSelector);
mobileTitleAndSelectorWrapper.style.display = "flex";
mobileTitleAndSelectorWrapper.style.flexDirection = "row";
mobileTitleAndSelectorWrapper.style.justifyContent = "space-between";
mobileTitleAndSelectorWrapper.style.alignItems = "center";
mobileTitleAndSelectorWrapper.style.marginBottom = "5px";
highwayArrowLeftContainer.style.width = "24px";
highwayArrowLeftContainer.style.height = "24px";
highwayArrowRightContainer.style.width = "24px";
highwayArrowRightContainer.style.height = "24px";
} else {
highwayArrowLeftContainer.style.width = "50px";
highwayArrowLeftContainer.style.height = "50px";
highwayArrowRightContainer.style.width = "50px";
highwayArrowRightContainer.style.height = "50px";
highwaySection.prepend(highwayTitle);
mobileTitleAndSelectorWrapper.remove();
highwaySection.appendChild(highwayPicSelector);
}
}
repositionHighwaySelectorForMobile();
breakPoint.addEventListener("change", () =>
repositionHighwaySelectorForMobile()
);
It works just fine, but later in my work I’ve found out that that exact section will be present in three instances with slightly different content, acting as slides to be horizontally scrolled.
I’ve created the slides by copypasting this section three times and now I have to teach this function to reposition the elements on each page as it does for the first. I understand that all variables are arrays with three elements now.
Is there an elegant way to do so? Or I have to rewrite each manipulation inside function to work with arrays?