tags:

views:

253

answers:

1
$('button').toggle({
    function(e){
        //turn on effects for all elements clicked
        $('*').toggle(
            function(e){
                //some nice effects when you click on elements
            },
            function(e){
                //nice effects turned off when you click again.
            }
        );
    },

    function(e){
        // turn off all effects. aka unbind all click event
    });
});

it doesn't quiet behave the way i expected. i wanted to basically

click the button effects are turned on when you click an element. its turned off when you click that element again.

click the button all effects are disabled.

however, what i end up with is

click the button effects are turned on when i click an element effects do not turn off when i click it again. effects turn off when i click once more.

also

click the button. effects turned on. click button again effects doesn't turn off. click button again effets turn off.

why does it do this ??

A: 

I'm not exactly sure I understand what you're trying to do, but my advice is to never use the $('*') selector. Do you really, really want your 'effects' to operate on EVERY DOM element in the page? Remember, that includes your "turn off/turn on" button.

I constructed an example which I think does what you're trying to do:

<head>
    <title>Test</title>
    <style type="text/css">
        .effectsOn {
            border: 1px solid blue;
            cursor: pointer;
        }
    </style>
    <script src="jquery.js"></script>
    <script type="text/javascript">
        $(function() {
            $("#btnToggle").toggle(function() {
                // turn on effects for all elements clicked
                $("li").addClass("effectsOn").toggle(function() {
                    // some nice effects when you click on elements
                    alert("test");
                },
                function() {
                    // nice effects disabled when you click again
                    $(this).removeClass("effectsOn").unbind();
                });
            },
            function() {
                // turn off all effects; aka unbind all click event
                $("li").removeClass("effectsOn").unbind();
            });
        });
    </script>
</head>
<body>
    <input type="button" id="btnToggle" value="Toggle effects" />
    <ul>
        <li>This is like, you know, a test.</li>
        <li>This is like, you know, a test.</li>
        <li>This is like, you know, a test.</li>
        <li>This is like, you know, a test.</li>
    </ul>
</body>

The key here was in using the "this" keyword to refer to the object being toggled, and (to reiterate what I said above) NOT using the $('*') selector.

Is this what you meant?

Pandincus