Flatsome Accordion Improvement
M
Michal
I have created the below function to improve accordion behavior slightly. Improves functionality and usability, by scrolling to top of opened tab.
Something to consider adding to your theme. Or maybe just for someone to use.
// improving Flatsome accordion by adding scroll to top of tab script (only on click to open, not close) MK
function flatsome_scroll_to_accordion_top_script() {
?>
<script>
document.addEventListener('DOMContentLoaded', function () {
function getStickyHeaderHeight() {
const header = document.querySelector('.header-wrapper.stuck'); // Flatsome sticky header
return header ? header.offsetHeight : 0;
}
function isInViewport(element) {
const rect = element.getBoundingClientRect();
return rect.top >= 0 && rect.top <= window.innerHeight / 2;
}
document.querySelectorAll('.accordion-title').forEach(function (title) {
title.addEventListener('click', function () {
const accordionItem = title.closest('.accordion-item');
setTimeout(function () {
const content = accordionItem.querySelector('.accordion-inner');
const isOpen = content && content.offsetHeight > 0;
if (accordionItem && isOpen && !isInViewport(accordionItem)) {
const stickyOffset = getStickyHeaderHeight();
const elementTop = accordionItem.getBoundingClientRect().top + window.scrollY;
window.scrollTo({
top: elementTop - stickyOffset,
behavior: 'smooth'
});
}
}, 400); // match animation timing
});
});
});
</script>
<?php
}
add_action('wp_footer', 'flatsome_scroll_to_accordion_top_script');