Andre
Andre

Reputation: 673

jquery - when toggle children do not toggle parent

I want to create a java-script-Drop-Down-Menu for a mobile site. The problem is, that when I click on a list-item in level2, by the toggle of level1 the list-item of level2 (and level3) gets closed, so I have to click at the list-item of level1 again to see level2 and level3. How can I deactivate the toggle of level1 if I click on a list-item of level2? Please point me to the right direction. Thank you!

Here's my html:

<div id="menu">
   <ul>
     <li class="level1"><a href="/xyz.html">
     <li class="level1"><a href="/xyz.html">    
        <ul>
           <li class="level2"><a href="/xyz.html">
           <li class="level2"><a href="/xyz.html">  
             <ul>
               <li class="level3"><a href="/xyz.html">
               <li class="level3"><a href="/xyz.html">
             </ul>
           <li class="level2"><a href="/xyz.html">
        </ul>
     <li class="level1">
     <li class="level1">
   </ul>
</div>

Here's my jquery:

$(document).on('pageinit',function(e,data){    
    // close menu if you go to another page
    $('#menu').hide(); 
    $('.level2').hide();
    $('.level3').hide(); 

    // Do not link if a sub-menu is present
    $('li:has(ul) > a').replaceWith(function() {
    return $(this).text();
    });

  // at click on menu-button scroll to top and open menu
  $(document).off('click', '#menuicon').on('click', '#menuicon',function(e) {
    $('html, body').stop().animate({ scrollTop : 0 }, 0);
    $('#menu').slideToggle(400);
  }); 

  // elements of the menu, different sub-menus width different classes
  $('#menu').on('click','.level1',function(e) { 
    $(this).find('.level2').slideToggle();
  });

  $('#menu').on('click','.level2',function(e) { 
    $(this).find('.level3').slideToggle();
  });

  $('#menu').on('click','.level3',function(e) {
    $('.level3').hide();
    $('.level2').hide();
    $('.level1').hide();
    $('#menu').hide();
  });

});

Upvotes: 0

Views: 446

Answers (1)

Rituraj ratan
Rituraj ratan

Reputation: 10378

use e.stopPropagation();

$('#menu').on('click','.level1',function(e) { 
e.stopPropagation();
    $(this).find('.level2').slideToggle();
  });

  $('#menu').on('click','.level2',function(e) { 
e.stopPropagation();
    $(this).find('.level3').slideToggle();
  });

  $('#menu').on('click','.level3',function(e) {
e.stopPropagation();
    $('.level3').hide();
    $('.level2').hide();
    $('.level1').hide();
    $('#menu').hide();
  });

Upvotes: 1

Related Questions