Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use toggle event with live?

Tags:

jquery

events

I have the following code

$(".reply").toggle
(
    function ()
    {
        x1();
    },
    function ()
    {
        x2();
    }
);

I need to use live, so new elements would also be bound. Is there some syntax to do it? Or will I need to implement a toggle on the click event?

I am using jQuery 1.4.2.

like image 500
BrunoLM Avatar asked Oct 01 '10 17:10

BrunoLM


2 Answers

Just modified fehay's answer so that it does not rely on jQuery not attaching duplicate event handlers during toggle()

$(".reply").live('click', function () {
    var toggled = $(this).data('toggled');
    $(this).data('toggled', !toggled);
    if (!toggled) {
        x1();
    }
    else {
        x2();
    }
});

Besides, just keep in mind that the selectors for live have to be as specific as possible because of the way event delegation works. Every time something gets clicked on the document, jQuery has to climb up the tree checking if the element matches the selector.For the same reason, .delegate() is much more performant because you can limit the capture area.

like image 89
Chetan S Avatar answered Nov 19 '22 20:11

Chetan S


live supports custom events in jquery 1.4. You could try something like this:

$(function () {
    $(".reply").live("customToggle", function () {
        $(this).toggle(
            function () {
                x1();
            },
            function () {
                x2();
            }
        );
    });

    $(".reply").live('click', function () {
        $(this).trigger('customToggle');
    });
});

this appears to work fine without a custom event:

$(".reply").live('click', function () {
    $(this).toggle(
            function () {
                x1();
            },
            function () {
                x2();
            }
        );
    $(this).trigger('click');
});
like image 3
fehays Avatar answered Nov 19 '22 20:11

fehays