Jump to content

Allowing menu dropdowns to open on hover


Alejandro

Recommended Posts

I asked AI for help with this and got the following script that can be added to the template's script tab, either head or footer. Feel free to play with it and share any improvements you make.

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Get all top-level dropdown items
    const dropdownItems = document.querySelectorAll('.nav-item.dropdown');
    
    dropdownItems.forEach(item => {
        // Handle mouse enter
        item.addEventListener('mouseenter', function(e) {
            // Find the hidden toggle span and trigger it
            const toggleSpan = this.querySelector('[data-bs-toggle="dropdown"]');
            if (toggleSpan && toggleSpan.getAttribute('aria-expanded') === 'false') {
                toggleSpan.click();
            }
        });

        // Optional: Handle mouse leave with small delay to prevent accidental closing
        item.addEventListener('mouseleave', function(e) {
            setTimeout(() => {
                // Check if the mouse is still outside the dropdown
                if (!this.matches(':hover')) {
                    const toggleSpan = this.querySelector('[data-bs-toggle="dropdown"]');
                    if (toggleSpan && toggleSpan.getAttribute('aria-expanded') === 'true') {
                        toggleSpan.click();
                    }
                }
            }, 200); // 200ms delay
        });
    });
});
</script>

 

  • Like 1
Link to comment
×
×
  • Create New...