Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery if li a hasClass

Tags:

jquery

I have a show/hide menu built. Which works great. But by default the menu is closed, again this is fine until the page is navigated to.

When the page is navigated to the a anchor is built with the class of "active", What I would like to is check if "active" exsists with the menu and display that block based on that. So at least one menu is always open.

My current jQuery is as follows :

    $('.sub_menu').hide();
$('.clickable').toggle(function(){
    $(this).next('ul').slideToggle();
    $(this).css('background-position','0px -12px');
}, function()
{
    $(this).next('ul').slideToggle();
    $(this).css('background-position','0px 5px');       
});

if ($('ul.sub_menu li a').hasClass('active')) {
    $(this).css('display','block');
}

I have also made a jsFiddle

So I am targetting if the ul.sub_menu li a = active and if it is show the sub_menu.

But not having any luck with it. Thanks in advance

like image 902
StuBlackett Avatar asked Mar 07 '26 06:03

StuBlackett


2 Answers

$('.sub_menu').hide();
$('.clickable').toggle(function(){
    $(this).next('ul').slideToggle();
    $(this).css('background-position','0px -12px');
}, function()
{
    $(this).next('ul').slideToggle();
    $(this).css('background-position','0px 5px');        
});

if ($('ul.sub_menu li a').hasClass('active')) {

    $('.sub_menu').css('display','block');
}

this work only if there is only one sub_menu..else you can use $(this).parent().parent().css()

like image 56
thecodejack Avatar answered Mar 08 '26 19:03

thecodejack


Just remove display:none from your ul.sub_menu and you can do a simple

$('ul.sub_menu li a:not(.active)').css('display', 'none');

DEMO

like image 20
Zoltan Toth Avatar answered Mar 08 '26 20:03

Zoltan Toth