Chezshire
Chezshire

Reputation: 713

Why doesn't the toggle toggle?

Newb here attempting to learn how to do work with jQuery by way of investigating 'the toggle'

I have a very simple html page and I thought that the second link would load as collapsed/hidden and that when clicked it would reveal it's contents, but it does not. Instead everything displays to the screen with all the inner html exposed (Hope i'm using terms correctly). I believe that what is happening is that the jQuery is not loading, but thats only the best guess of a hobbyist, hopefully someone out there can help me to get this to work.

<html>
<head>
    <script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>

    <script>
        $.fn.slideFadeToggle = function(speed, easing, callback) {
            return this.animate({
                opacity: 'toggle',
                height: 'toggle'
            }, speed, easing, callback);
        };

        // Collapse everything but the first menu:
        $("#accordionMenu  li  a").not(":first").find("+ ul").slideUp(1);

        // Expand or collapse:
        $("#accordionMenu  li  a").click(function() {
            $(this).find("+ ul").slideFadeToggle("500");
        });
    </script>

</head>
<body>
    <div id="firstDiv">
        <div id="secondDiv">
            <ul id="accordionMenu">
                <li><a href="#">menu item</a></li>
                <li><a href="#">menu item</a>
                    <ul>
                        <li><a href="#">suboption 1</a></li>
                        <li><a href="#">submenu expandable</a>
                        <ul>
                            <li><a href="#">suboption 1</a></li>
                            <li><a href="#">suboption 2</a></li>
                        </ul>
                    </li>
                    </ul>
                </li>
            </ul>
        </div>
    </div>
</body>

Upvotes: 0

Views: 72

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388406

Your code need to be in a dom ready handler. In your case you are trying to add the event handler to the target elements before those elements are loaded in the dom, so those handlers will not get registered.

//dom ready handler
jQuery(function ($) {
    $.fn.slideFadeToggle = function (speed, easing, callback) {
        return this.animate({
            opacity: 'toggle',
            height: 'toggle'
        }, speed, easing, callback);
    };

    // Collapse everything but the first menu:
    $("#accordionMenu  li  a").not(":first").find("+ ul").slideUp(1);

    // Expand or collapse:
    $("#accordionMenu  li  a").click(function () {
        //use .next() here
        $(this).next("ul").slideFadeToggle("500");
    });
})

Demo: Fiddle

Upvotes: 2

Related Questions