Search code examples
javascripthtmlmobilemenunav

Parent menu link # reloads the page instead of triggering submenu


How to prevent page reloading when empty link is pressed (href="#") it will just reload the page without triggering submenu.

Thank you in advance


Solution

  • Use javascript:void(0); instead of # to prevent the page from reloading and then when the link is clicked you need to trigger the click event of its parent element :

    <a href="javascript:void(0);" onclick="event.target.parentElement.click()">Produkter</a>
    

    The below code is your event listener which is assigned to parent element of link, it returns false when event.target.nodeName is A

    'click_nav_child': function(e) {
        if (e.target.nodeName == 'A')
            return false;
        var string = '';
        string += '<nav class="side-nav">';
        string += '<ul>';
        string += '<li class="prev"><a href="#">' + this.querySelector('a').textContent + '</a></li>' + this.querySelector('ul').innerHTML;
        string += '</ul>';
        string += '</nav>';
        var el = document.createElement("div");
        el.classList.add('nav-slide');
        itc_navigation.wrapper.appendChild(el);
        var slides = itc_navigation.get_slides();
        var last_slide = slides[slides.length - 1];
        last_slide.innerHTML = string;
        itc_navigation.change_slide('next');
        e.preventDefault();
        return false;
    }