4
\$\begingroup\$

I am writing some code to turn a multi level UL into an accordion:

$(document).ready(function () {
$('.s4-ql li ul').each(function (index) {
 $(this).hide();
});
$('.s4-ql ul li ul').each(function (index) {
 var length = 0;
 length = $(this).children().length;
 var CurrentItem = $(this).parent().find('a:first');
 CurrentItem.find('.menu-item-text').append('<span style=\'float:right;font-size:0.8em;\'>(' + length + ')</span>');
});
$('.s4-ql ul li').hover(
 function () {
 $(this).find('a:first').next().slideToggle('normal');
 },
 function () {
 $(this).find('a:first').next().slideToggle('normal');
 }
);
});

Can anyone tell me whether I am being relatively efficient or whether there is anywhere that I can "trim the fat", so to speak? The code also counts the number of children and displays that number on the main parent.

200_success
146k22 gold badges190 silver badges479 bronze badges
asked Dec 15, 2011 at 15:10
\$\endgroup\$
3
  • 1
    \$\begingroup\$ Also, speaking of "trimming the fat", please don't write tags in titles and signatures in questions. \$\endgroup\$ Commented Dec 15, 2011 at 15:13
  • \$\begingroup\$ What do you mean Tom? sorry? - As for code review..thx for that link, was not aware of it. \$\endgroup\$ Commented Dec 15, 2011 at 15:18
  • \$\begingroup\$ @user257503: I mean, please don't write tags in titles (like "jQuery: "), and signatures/thanks are not required (and will be edited out) as you're writing a question not an email! ta [not the same for comments :P] \$\endgroup\$ Commented Dec 15, 2011 at 15:23

2 Answers 2

3
\$\begingroup\$

It'll be good if you can provide your HTML markup. Without it I can do this:

jQuery(function($) {
 $('.s4-ql li ul').hide();
 $('.s4-ql ul li').hover(function() {
 $(this).find('a:first').next().slideToggle();
 }, function() {
 $(this).find('a:first').next().slideToggle();
 }).find('ul').each(function(index) {
 var $this = $(this);
 $this.parent().find('a:first .menu-item-text').append(['<span style=\'float:right;font-size:0.8em;\'>(', $this.children().length, ')</span>'].join(''));
 });;
});
answered Dec 15, 2011 at 15:24
\$\endgroup\$
0
1
\$\begingroup\$

All jQuery mutation methods operate on every element in the set.
You can just write $('.s4-ql li ul').hide(); you don't need .each.

Also, you should just write var length = $(this).children().length; in one line.

answered Dec 15, 2011 at 15:13
\$\endgroup\$
0

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.