[Dropdown] Menu JS & CSS / Code Injection

Hi!
I would like to introduce you to the working dropdown menu that I use in the Source template.
First, let’s prepare the code that we need to inject into the header and footer.

How it’s look like:
image

Configuration at navigation

Code injection
Header

<style>
.nav .nav-categories .dropdown-content {
    display: none;
    position: absolute;
    background-color: #fff;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}

.nav .nav-categories:hover .dropdown-content {
    display: block;
}

.nav .nav-categories .dropdown-content a {
    color: #333;
    padding: 12px 16px;
    display: block;
}
</style>

Footer

<script>
document.addEventListener('DOMContentLoaded', function() {
    var mainCategories = document.querySelectorAll('.nav-categories');
    mainCategories.forEach(function(mainCategory) {
        var dropdownContent = mainCategory.querySelector('.dropdown-content');
        if (!dropdownContent) {
            dropdownContent = document.createElement('div');
            dropdownContent.className = 'dropdown-content';
            mainCategory.appendChild(dropdownContent);
        }
        var subCategories = mainCategory.parentNode.querySelectorAll('[class^="nav-categories-"]');
        subCategories.forEach(function(subCategory) {
            if (!subCategory.classList.contains('dropdown-content')) {
                var categoryName = subCategory.textContent.replace('Categories-', '');
                var newLink = document.createElement('a');
                newLink.href = subCategory.querySelector('a').href;
                newLink.textContent = categoryName;
                dropdownContent.appendChild(newLink);
                subCategory.style.display = 'none';
            }
        });
    });
});
</script>

Have a good day!

1 Like