MrPink
MrPink

Reputation: 1371

jquery nav bar slidetoggle issue

I'm fairly new to jquery and so far i have got my code to toggle and slide a html menu. heres my code

<script type="text/javascript">
$(document).ready(function () {
    $('li').each(function(){
$('li.menuheader').hover(function(){
    $('ul.submenu').slideToggle('slow', function(){})
});
}); 

});
</script>
</head>
<body>
<div id="navbar">
  <ul>


    <li class="menuheader">test1
      <ul class="submenu">
        <li>item 1</li>
        <li>item 2</li>
        <li>item 3</li>
        <li>item 4</li>
      </ul>
    </li>


    <li class="menuheader">test2
      <ul class="submenu">
        <li>item 1</li>
        <li>item 2</li>
        <li>item 3</li>
        <li>item 4</li>
      </ul>
    </li>


    <li class="menuheader">test3
      <ul class="submenu">
        <li>item 1</li>
        <li>item 2</li>
        <li>item 3</li>
        <li>item 4</li>
      </ul>
    </li>


  </ul>
</div>

</body>
</html>

my jquery dropdowns every menu everytime the mouse hovers over a menuheader. I need to seperate these out without using div id's and making seperate jquery functions. Can anyone help me with how to do this?

Upvotes: 0

Views: 1592

Answers (3)

pimvdb
pimvdb

Reputation: 154958

Your code shows all ul.submenu because they all match the selector. Use $(this).find('ul.submenu') to find the appropriate ones for each li.

Secondly, for each li you bind a hover handler for each li.menuheader. That's unnecessary.

Also, hover triggers at mouseenter and mouseout. mouseenter should suffice,

$(document).ready(function () {
    $('li.menuheader').mouseenter(function() {
        $('ul.submenu').not(this).slideUp('slow'); // hide all
        $(this).find('ul.submenu').slideDown('slow'); // 
    });
});

http://jsfiddle.net/zRvLt/

Upvotes: 0

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76910

Maybe this is what you are looking for (n need to use slideToggle i think):

$('ul.submenu').hide();
$('li').each(function() {
    $('li.menuheader').hover(function() {
        $(this).find('ul.submenu').show('slow')
    }, function() {
        $(this).find('ul.submenu').hide('slow')
    });
});

fiddle here: http://jsfiddle.net/DRjPF/

Upvotes: 1

Talha Ahmed Khan
Talha Ahmed Khan

Reputation: 15473

$('li.menuheader') ==> this will select all the menuheaders. Filter them with this.

$(document).ready(function () {
    $('li').each(function(){
        $(this).('menuheader').hover(function(){
            $(this).children('ul.submenu').slideToggle('slow', function(){
                ....
            })
        });
    }); 
});

Upvotes: 0

Related Questions