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);
 });
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Mar 29, 2012 at 9:31
\$\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.

answered Mar 29, 2012 at 13:05
\$\endgroup\$
0
1
\$\begingroup\$

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

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

answered Mar 29, 2012 at 12:55
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.