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! " />');
});
}());
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");
});
}());