views:

71

answers:

4

Hi,

Is there a way I can use the 'bind' syntax for the 'toggle' event handler ?

From the docs I can understand that the correct way is

$('.selector').toggle( function() {}, function() {} );

My problem is that I am removing that element for some reason, and then again add it to the DOM. On adding it again, the toggle does not work.

Thus, I think there should be a way to 'bind' the toggle.

Help please.

This is documentation I am following: http://jqapi.com/#p=toggle

+4  A: 

My problem is that I am removing that element for some reason, and then again add it to the DOM. On adding it again, the toggle does not work.

I think, it depends on how exactly you remove element. If you use remove function, all events and jquery data will be removed from element too. And it's opposite with detach function, making it ideal for removing elements you plan to insert back in the document later.

Nikita Rybak
+1 for suggesting to use of `.detach()`, since that would allow the native use of `.toggle()`.
Peter Ajtai
This is exactly how it works in my code. Perfect!
Hrishikesh Choudhari
+2  A: 

Refer : .bind , .trigger

$(function() {
  $('input').click(function() {
    $('#id').trigger('toggle')
  });
    $('#id').bind('toggle', function() {
       $(this).toggle()
    });
});

Try the Example : http://jsbin.com/ixapo4/2

Ninja Dude
The OP is asking about dynamically added elements. This method doesn't work with those. From the OP: `My problem is that I am removing that element for some reason, and then again add it to the DOM`
Peter Ajtai
... and if the elements are taken out of the DOM with `.detach()`, then there is no reason for the above, since `.toggle()` may simply be used on the original elements.
Peter Ajtai
you can see the title of the op question as `How to bind the 'toggle' event to a element`
Ninja Dude
@Avinash - `How to bind the 'toggle' event to an element` is `$(elementSelector).toggle();` ------ In other words your code can be simplified to ==> `$('input').click(function() { $('#id').toggle(); });` -------- http://jsfiddle.net/fwsEc/ ------- But that's only the title of the question. The body of the question describes more of the problem.
Peter Ajtai
+2  A: 

Try to use live function. Here is documentation. link text

Hope it will help you.

rajakvk
Exactly use the live() function of jQuery, every time an new element is added to your selector defined previously it will be attached with the event you did before. ;)
Darkxes
`.live()` binds an action. `.toggle()` is a jQuery method that binds the `click` action. I'm not sure how to use `.live()` to bind `.toggle()`. Could you provide an example?
Peter Ajtai
+2  A: 

You must use either .live() or .delegate() to add handlers to all now and future elements.

The problem is that .toggle() binds click, and in complicated cases, like using .live() or .delegate() you have to make your own. From the jQuery Docs:

The .toggle() method is provided for convenience. It is relatively straightforward to implement the same behavior by hand, and this can be necessary if the assumptions built into .toggle() prove limiting.

Roll your own toggle (this can be easily extended to N toggled functions using mod N instead of mod 2 - but then you have to use a switch instead of the JS conditional operator):

var counter = 1;
$('.selector').live("click", function() {
    counter++ % 2 ? 
        // First set of actions :
        // Second set of actions;            
});

If you want to include 2 functions, then they must be self executing. This would be good for passing arguments in... so the form would be:

var counter = 1;
$('.selector').live("click", function() {
    counter++ % 2 ? 
        (function() { ... }()) :                            // <== First function
        (function() { ... }());                            // <== Second function
});


A simple example (no arguments used):

(function() {
    var counter = 1;
    $('.selector').live("click", function() {
        counter++ % 2 ? 
            $("div").html("First one!") :
            $("div").html("Numero dos!");

        });
    $(function() {
        $("body").prepend('<input type="button" ' + 
                          'class="selector" value=" Click Me! " />');
    });
}());

try it out on jsFiddle


A more complex example (arguments used):

(function() {
    var counter = 1;
    $('.selector').live("click", function() {
        // Note that the self executing functions are only
        // necessary if you want to use arguments.
        counter++ % 2 ? 
            (function() {
                $("div").html("First one! Num: " + ($(event.target).index() + 1))
            }(event)) :
            (function() {
                $("div").html("Numero dos! Num: " + ($(event.target).index()+1))
            }(event));            
        });
    $(function() {
        $elie = $('<input type="button" class="selector" value="Click Me!" />');
        $elie.clone().prependTo("body");
        $elie.clone().prependTo("body");
        $elie.clone().prependTo("body");        
    });
}());

try it out on jsFiddle

Peter Ajtai
@Peter: Thanks a lot for your detailed analysis and very helpful code. It really helped!
Hrishikesh Choudhari
@Hrishikesh - You're welcome ;)
Peter Ajtai