Rotan075 Rotan075 - 6 months ago 33
Javascript Question

Toggle class on generated toggle element

I have a situation where I get a bit stuck and where I need some help. Let me explain myself by some code. I have the following HTML setup:

<button type="button" class="navbar-toggle collapsed"></button>
<div class="collapse navbar-collapse" tabindex="-1">
<div class="nav navbar-nav" tabindex="-1">
<div class="menuitem_wrapper" tabindex="-1">
<a href="#" class="">Menu 1</a>
<div class="dropdown-menu" tabindex="-1">
<a href="#">Sub 1.1</a>
<a href="#">Sub 1.2</a>
</div>
</div>
<div class="menuitem_wrapper" tabindex="-1">
<a href="#" class="">Menu 2</a>
<div class="dropdown-menu" tabindex="-1">
<a href="#">Sub 2.1</a>
<a href="#">Sub 2.2</a>
</div>
</div>
</div>
</div>


I have build in some functionality with jQuery:

$(document).ready(function() {

$(".collapsed").click(function() {
$(".navbar-collapse").toggleClass('show-menu');
$(".menuitem_wrapper").removeClass('menuitem_wrapper').addClass('menuitem_wrapper_mobile');
});

$(".menuitem_wrapper").click(function() {
$(this).find(".dropdown-menu").removeClass('dropdown-menu').addClass('dropdown-menu-mobile');
});

});


The functionality triggers whenever toggle button is pressed the hyperlinks: menu 1 and menu 2 are shown (the sub items are hidden via CSS).

The first part which I do not fully understand is why this works:

$(".menuitem_wrapper").click(function() {
$(this).find(".dropdown-menu").removeClass('dropdown-menu').addClass('dropdown-menu-mobile');
});


and why this not:

$(".menuitem_wrapper_mobile").click(function() {
$(this).find(".dropdown-menu").removeClass('dropdown-menu').addClass('dropdown-menu-mobile');
});


But the main problem that I have is whenever I press on the hyperlink: menu 1 or menu 2 the submenu is showed. But I want to create the functionality of having a toggle effect.

The hard part in creating this code is that I can not add any CSS classes manually to the divs. Because this menu is used in two ways. As a mobile menu which is presented to the user vertically and as a default menu which is presented horizontal with hover effects.

Can anyone help me getting the desired effect, toggling, without having to add classes to my HTML code.

JSFIDDLE OVER HERE

Answer

Javascript

$(document).ready(function() {

    $(".collapsed").click(function() {
        $(".navbar-collapse").toggleClass('show-menu'); 
        $(".menuitem_wrapper").removeClass('menuitem_wrapper').addClass('menuitem_wrapper_mobile');
    });

    $(".menuitem_wrapper a:first-child").click(function() {         
        $(this).parent().children("div").toggleClass('dropdown-menu dropdown-menu-mobile');     
    });

});

Fiddle