Is there a way I can call the second function in toggle(function(){},function(){})
-
what do you want to achieve with this ?Nealv– Nealv2010-07-30 11:23:46 +00:00Commented Jul 30, 2010 at 11:23
-
I have a toggle with two functions and for a specific case I want the second function to be called and set the state of the toggle() to the second functionchchrist– chchrist2010-07-30 11:39:12 +00:00Commented Jul 30, 2010 at 11:39
-
I show how to do this below, but wouldn't using a named function, reversing the order and calling that now-first named function be easier?Nick Craver– Nick Craver2010-07-30 12:05:59 +00:00Commented Jul 30, 2010 at 12:05
Add a comment
|
3 Answers
You could skip the toggle to the next function, if you really wanted to I suppose, for example:
$("div").toggle(function() {
alert("First");
}, function() {
alert("Second");
});
Then you can manually advance the .toggle() function array (without calling the first function), like this:
$("div").data('lastToggle' + $("div").data().events.click[0].handler.guid, 1);
Then just click the element or $("div").click(), etc, and it'll fire the second function.
You can give it a try here, note that this only works in jQuery 1.4+ and is really just to show it's possible. You should however either bind them in reverse order, or give the second argument a named function as the other answers suggest.
1 Comment
Nick Craver
@Avinash - If you look at how
.toggle() works internally it's much easier to understand: github.com/jquery/jquery/blob/master/src/event.js#L904 All we're doing it setting a data variable it's looking for when the click event happens. The click isn't bound to any of the functions you pass, rather it's bound to another wrapper function that gets/runs the function it's currently on (via .apply()). We're just setting the start position it stores before the first click event happens, so it finds it and executes the second function on the first pass.