Question

Heelo everyone, i never worked with javascript before, and i'm developing an accordion menu. It's working fine when i use the function click. but when i try to load a page with an li a with the class="active", the function above doesn't work. Am i using the ready function uncorretly?

Hope for some help. Thanks!

<script>
    $(document).ready(function () {
      $('#nav > li > a').click(function(){
        if ($(this).attr('class') != 'active'){
          $('#nav li ul').slideUp();
          $(this).next().slideToggle();
          $('#nav li a').removeClass('active');
          $(this).addClass('active');
        }
      });
      $('#nav > li > a').ready(function(){
        if ($(this).attr('class') == 'active'){
            $('#nav li ul').slideUp();
          $(this).next().slideToggle();

        }
      });
    });
    </script>
Was it helpful?

Solution

Try this:

$('#nav > li').each(function(){
    if($(this).find('a').hasClass('active')){
        $(this).find('ul').slideDown();
    }
});

or

$('#nav > li > a').each(function(){
    if($(this).hasClass('active')){
        $(this).parent().find('ul').slideDown();
    }
});

Instead of this

$('#nav > li > a').ready(function(){
    if ($(this).attr('class') == 'active'){
        //your code here
    }
 });

Fiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top