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.

\$\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\$
    – user257503
    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(''));
    });;
});
\$\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.

\$\endgroup\$
0

Your Answer

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

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