0

I'm currently struggling fixing my jQuery script on the sidebar. The site can be found here .

What I'm trying to achieve is to make the sidebar toggle work on each parent 'li' element that has a child 'ul'.

Parent menu item should not redirect unless it has expanded. Same thing also should happen on the submenu items that have child menu items. Menu items that has not child 'ul' should redirect.

My jQuery code is:

    $('.textwidget .sub-menu .sub-menu').hide(); 
    $('.textwidget .sub-menu li').has('ul.sub-menu').each(function(){
        $(this).addClass('expand');
    });

    $('.widget_text > div > ul.sub-menu li').addClass('dead');

    $('.widget_text > div > ul.sub-menu li:has(ul)').click(function(e){

        if ( $(this).hasClass("expand") ) {
            $(this).removeClass('expand');
            $(this).addClass('collapse');
        }
        else{

            $(this).addClass('expand');
            $(this).removeClass('collapse');

        }
        $(this).find('ul').first().slideToggle();
        return false;
        //console.log($(this).closest('li.expand').attr('class'));
    });

    $('.widget_text > div > ul.sub-menu li a').click(function(e){

        if ( $(this).next('ul').is(":hidden") ) {
            e.preventDefault();
        }
        else{
            $(this).closest('ul').stop(true,false);
        }
        //console.log($(this).closest('li.expand').attr('class'));
    });

Currently, its not redirecting at all because of the return false; statement.

Any suggestion to make this piece of code work correctly?

1 Answer 1

1

As I understand your script can be simplifed to this:

$('.textwidget .sub-menu .sub-menu').hide();
$('.widget_text > div > ul.sub-menu li').addClass('dead');
$('.textwidget .sub-menu li').has('ul.sub-menu').removeClass('dead').addClass('expand');    

$('.widget_text > div > ul.sub-menu li:has(ul)').click(function (e) {
    var $li=$(this);
    if ($li.hasClass("expand")) {     //if clicked menu not expanded    
            e.stopPropagation();
            e.preventDefault();
    } else {
        if ($(e.target).parent().is('a')) {return;} //if menu expanded and we click on link
    }
    $li.toggleClass("expand collapse").children('ul').first().slideToggle();

});

Demo

Sign up to request clarification or add additional context in comments.

1 Comment

Wow. Thanks man. You're a legend. Your code is really helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.