views:

966

answers:

1

The code expands and collapses a list in which list items can have sublists. Any ideas to refactor this code - especially the toggling part. Is it necessary to use closures here ?

$(function()
{
    $('li:has(ul)')
    .click(function(event){
        if (this == event.target) 
        {
            var that = this;
            $('li:has(ul)').children().filter(':not(:hidden)').parent().each(function(x){
                if(this != that)
                    toggleList(this);
            });
            toggleList(this);
        }
    })
    .css({cursor:'pointer', 'list-style-image':'url(plus.gif)'})
    .children().hide();

    $('li:not(:has(ul))').css({cursor: 'default', 'list-style-image':'none'});
}); 
function toggleList(L)
{
    $(L).css('list-style-image', (!$(L).children().is(':hidden')) ? 'url(plus.gif)' : 'url(minus.gif)');
    $(L).children().toggle('fast');
}

EDIT:

The script works on the following HTML snippet (source: jQuery in Action). Actually I was trying to extend the script given in the book.

      <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>
          Item 3
          <ul>
            <li>Item 3.1</li>
            <li>
              Item 3.2
              <ul>
                <li>Item 3.2.1</li>
                <li>Item 3.2.2</li>
                <li>Item 3.2.3</li>
              </ul>
            </li>
            <li>Item 3.3</li>
          </ul>
        </li>
        <li>
          Item 4
          <ul>
            <li>Item 4.1</li>
            <li>
              Item 4.2
              <ul>
                <li>Item 4.2.1</li>
                <li>Item 4.2.2</li>
              </ul>
            </li>
          </ul>
        </li>
        <li>Item 5</li>
      </ul>
+1  A: 

Your code doesn't work for me in Safari. When I click on a sub-list, the top-list is toggled.

How about:

$(document).ready(function() {
  $('li:has(ul)').click(function(event) {
    $(this).css('list-style-image', $(this).children().is(':hidden') ? 'url(minus.gif)' : 'url(plus.gif)')
    $(this).children().toggle('fast')
    return false
  })
  .css({cursor:'pointer', 'list-style-image':'url(plus.gif)'})
  .children().hide()

  $('li:not(:has(ul))').click(function(event) { return false })
  .css({cursor:'default', 'list-style-image':'none'})
})
Zach Langley