javascriptwordpressdrop-down-menuslidetogglesiblings

JavaScript .siblings method doesn't work in mobile menu with drop-down sub-links in Wordpress


On website bemchemia.pl I have a Wordpress mobile menu with drop-down sub-links. I want to reveal sublinks using JavaScript .slideToggle only by clicking an arrow and not by clicking a parent link. Now sublinks reveals when I click either arrow or parent link.

Function below works, but I don't want to reveal sub-links by clicking a parent link.

$(function () {
    $(".menu-mobile__nav .sub-menu").hide();

    $(".menu-mobile__nav .menu-item-has-children").click(function () {
        $(this).children(".sub-menu").slideToggle('');
    });
});

Similar function below should resolve my problem, but it doesn't work at all. Where is the problem?

$(function () {
    $(".menu-mobile__nav .sub-menu").hide();

    $(".menu-mobile__nav .menu-item-has-children .arrow").click(function () {
        $(this).siblings(".sub-menu").slideToggle('');
    });
});

Current shortended html code copied from website:

<div class="menu-mobile">
    <div class="menu-mobile__nav" id="nav">
        <li class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-has-children menu-item-669"><a
                href="https://bemchemia.pl/./docieplenia">Docieplenia</a><span class="arrow"></span>
            <ul class="sub-menu" style="display: none;">
                <li class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1364"><a
                        href="https://bemchemia.pl/./docieplenia/tynki">Tynki</a><span class="arrow"></span></li>
                <li class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1365"><a
                        href="https://bemchemia.pl/./docieplenia/kleje">Kleje</a><span class="arrow"></span></li>
                <li class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1366"><a
                        href="https://bemchemia.pl/./docieplenia/farby-elewacyjne">Farby elewacyjne</a><span
                        class="arrow"></span></li>
            </ul>
        </li>
    </div>
</div>

Solution

  • I did some testing with your page and I discovered that the .arrow elements are loaded dynamically after the page loads. As a result, your selector doesn't work. All you have to do is replace this line

    $(".menu-mobile__nav .menu-item-has-children .arrow").click(function () {
    

    with this:

    $(".menu-mobile__nav .menu-item-has-children").on('click', '.arrow', function () {