Search code examples
javascriptjquerypreventdefault

javascript preventDefault only on parent item


I am creating a drop down nav in javascript. Any list items that have children i would like to prevent the default action and do something else. I have this working but when applied the default action is also applied to the child list items.

Here is my HTML:

<i id="mobnavtrig" class="fa fa-align-justify fa-2x"></i>
    <div class="mobilenav">
        <li class="page_item page-item-2"><a href="/">Home</a></li>
        <li class="page_item page-item-10"><a href="?page_id=10">Who We Are</a></li>
        <li class="page_item page-item-25 page_item_has_children current_page_item parent"><a href="?page_id=25">Case Studies</a>
            <ul class='children'>
                <li class="page_item page-item-55"><a href="?page_id=55">Barratt Developments</a></li>
                <li class="page_item page-item-53"><a href="?page_id=53">Care in Bathing</a></li>
            </ul>
        </li>
        <li class="page_item page-item-27"><a href="?page_id=27">Blog</a></li>
        <li class="page_item page-item-29"><a href="?page_id=29">Get In Touch</a></li>
    </div>

Here is my JS:

$( ".mobilenav li.parent" ).click(function(event) {
        if($(this).hasClass('page_item_has_children')){
            event.preventDefault( );
            $(this).addClass('current_page_item');
            $(this).find('.children').slideToggle("fast");
        }
    });

Is there something i am missing in the above?


Solution

  • in children click you have to use stopPropagation() to stop event bubbling

    $( ".mobilenav li.parent .children" ).click(function(e){
      e.stopPropagation();
    
    });