2
\$\begingroup\$

This code works great and does exactly as it should, but there has to be a better way of doing this and I just can't figure out how!

I'm pretty new to jQuery and am trying to use it more myself instead of using plugins and I can get stuff to work fine. It just isn't the tidiest or neatest code, which I'm trying to move away from!

I've included a fiddle here just so you can see the functionality as it currently stands.

HTML

<ul>
    <li>Example 1</li>
    <li class="open">Example 2
        <ul>
            <li>Sub Example 2.1</li>
            <li>Sub Example 2.2</li>
            <li>Sub Example 2.3</li>
            <li>Sub Example 2.4</li>
        </ul>
    </li>
    <li class="open2">Example 3
        <ul>
            <li>Sub Example 3.1</li>
            <li>Sub Example 3.2</li>
            <li>Sub Example 3.3</li>
        </ul>
    <li>
</ul>

jQuery

var menu = $('li.open ul');
menu.css('display','none');
     $('li.open')
     .mouseenter(function(){
          menu.slideDown(400);
     })
     .mouseleave(function(){
          menu.slideUp(400);
     });

var menu2 = $('li.open2 ul');
menu2.css('display', 'none');
    $('li.open2')
    .mouseenter(function(){
         menu2.slideDown(400);
     })
     .mouseleave(function(){
         menu2.slideUp(400);
     });
\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

Instead of selecting .open and .open2, you could change your selector to see if there is a child <ul>.

$('li:has(ul)').hover(function() {
  $(this).find('ul').slideDown(400);
}, function() {
  $(this).find('ul').slideUp(400);
})

Edit: you can also hide all the child <ul> nodes at once instead of individually.

$('li ul').hide();

Reference

Here are the three main features of jQuery that I used. Each link uses <api.jquery.com> which is a great place to learn about various jQuery functions.

\$\endgroup\$
0
0
\$\begingroup\$

Instead of mouseenter/mouseleave, you can use hover. It combines both events.

.css('display','none'); can be done with .hide();

\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.