I am facing one problem, where I have created accordions/faq items which you can toggle (open & close) and switch to another one and close the previous one which works fine. But the issue here is if I resize my browser or change the orientation mode to landscape or portrait the max-height is not re-calculated.
I have created a function "accordionHeight" which works onClick but I am unable to pass the "item" to this function to re-calculate outside my click event.
Because the height will obviously only change on click. But I want it to re-calculate on rotate of the current open "item__box" but it's outside the scope.
I have a real example on Codepen instead of code.
My JS:
(() => {
const accordion = document.querySelector('[bke-data="accordion"]');
if (!accordion) {
return;
}
const items = accordion.querySelectorAll('.accordion__item');
const accordionHeight = (element, elementHeight) => {
element.style.setProperty(`--max-height`, `${elementHeight}px`);
};
const toggleAccordion = (item) => {
const itemBox = item.querySelector('.accordion__box');
const itemBoxHeight = itemBox.scrollHeight;
const openItems = accordion.querySelectorAll('.open');
const itemsLength = openItems.length;
const currentItem = item;
// itemBox.style.setProperty(`--max-height`, `${itemBoxHeight}px`);
accordionHeight(itemBox, itemBoxHeight);
if (itemsLength) {
openItems.forEach((item) => {
item !== currentItem && item.classList.remove('open');
});
}
item.classList.toggle('open');
};
items.forEach((item) => {
item.addEventListener('click', () => toggleAccordion(item));
});
window.addEventListener('resize', accordionHeight);
})();
Codepen full code + example: https://codepen.io/Merdzanovich/pen/MWvaryG
Please, see below example of resize event handling. Note: Run snippet in full page mode
<!DOCTYPE html>
<html>
<body onresize="myFunction()">
<p>Try to resize the browser window to display the windows height and width.</p>
<p id="demo"></p>
<p><strong>Note:</strong> this example will not work properly in IE8 and earlier. IE8 and earlier do not support the outerWidth/outerHeight propery of the window object.</p>
<script>
function myFunction() {
var w = window.outerWidth;
var h = window.outerHeight;
var txt = "Window size: width=" + w + ", height=" + h;
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>