jQuery 1.3.2 Toggle Element Issue

So here's a little obscurity I ran across in using jQuery 1.3.2 to affect effects on an unordered list.

Here's what I've got:

<!doctype html>

<html>

    <head>

        <script>

            $(".bb_qlist_title").click(function(){

                $(this).siblings('ul').slideToggle(function(){

                    var visible = $(this).is(':visible');

                    if( visible ){

                        $(this).siblings('h4').css('background-image', –>

                            'url(lib/images/content/icons/bullet_arrow_down.png)');

                    }else{

                        $(this).siblings('h4').css('background-image', –>

                            'url(lib/images/content/icons/bullet_arrow_up.png)');

                    }

                });

            });

        </script>

    <head>

    <body>

        <ul>

            <li><h4>Title</h4>

                <ul>

                    <li>menu item</li>

                    <li>menu item</li>

                    <li>menu item</li>

                 </ul>

            </li>

        </ul>

    </body>

</html> 

Pretty streight forward you'd say. We're building a list and sub-list. The sub-list get's slid up when the user clicks on the h4 element. We're also wanting to change a background-image of the h4. In this case the images used are up and down arrows.

But here's the kicker, the above code will not work. The problem line is "var visible = $(this).is(':visible');". Here's what's going on.

The UL that contains our sub-list elements has no box size. In jQuery 1.3.2 the toggle methods no longer look at the CSS visibility of an element, but rather the visible area that element takes up on the page. Since the UL doesn't take up any area, the above line is always false.

Now there are two ways around this pickle.

  1. If like you could give the sub-list UL some dimensions.
  2. or we can just watch for it's children.

The 2nd option seams the most rhobust to me since we don't know how many list items our sub-list will hold, so setting a height is not an option.

So the simple fix is to change this line:

var visible = $(this).is(':visible');

to this line:

var visible = $(this).children('li').is(':visible');

We're now watching the sub-lists children LIs which do take up physical space on the page and jQuery 1.3.2 can see them.

Leave a Reply

Your email address will not be published. Required fields are marked *