Question

I am trying to mimic a dependent select list using unordered lists and jQuery so i can style my lists how I want because I can't style select lists.

The problem i'm having is if the second menu is open and i click on the first menu, i need the second menu to close before opening the first.

This is the bit i think is cusing the problem.

if($("#next_menu").is(':visible')) {
    $("#next_menu").slideToggle(200);
}

Also, is there a way i can improve the code to make it more efficient like chaining events? I've seen people do code in only a couple of lines and don't know if this is possible with what i've got.

JQUERY

$(document).ready(function() {
    // hide the menu on page load
    $('#current_menu').hide();
    // hide each of the linked menus on page load
    $('#next_menu > ul').each(function() {
        $(this).hide();
    });

    $("#current_page").click(function() {

        if($("#next_menu").is(':visible')) {
            $("#next_menu").slideToggle(200);
        }
        // slide up/down the first menu
        $("#current_menu").slideToggle(200);
    });

    $("#current_menu li").click(function(event) {
        // set the text of div to what was clicked
        $("#current_page").html($(this).text());

        // get the id if the clicked <li>
        var id = $(this).attr('id');

        //slide up the first menu
        $("#current_menu").slideToggle(200, function() {

            $("ul." + id).show();
        });
    });
});

HTML

<div class="aaa">
    <div id="current_page">Default Value</div>
    <div id="current_menu">
      <ul>
        <li id="a"><a href="#">Option A</a></li>
        <li id="b"><a href="#">Option B</a></li>
        <li id="c"><a href="#">Option C</a></li>
      </ul>
    </div>
</div>
<div class="aaa">
    <div id="next_page">Default Value</div>
    <div id="next_menu">
        <ul class="a">
            <li>Lipsum</li>
            <li>Lipsum</li>
            <li>Lipsum</li>
        <ul></ul>
        <ul class="b">
            <li>Lipsum</li>
            <li>Lipsum</li>
            <li>Lipsum</li>
        </ul>
        <ul class="c">
            <li>Lipsum</li>
            <li>Lipsum</li>
            <li>Lipsum</li>
        </ul>
    </div>
</div> 
Was it helpful?

Solution

Add same class in the menus like .menus

$('.menus').click(function(){
  if(!$(this).is(':visible'){
   $('.menus').hide();
   $(this).show();
  }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top