I am using the toggle() method on buttons so that they can have a do something / revert changes behaviour. For instance:
$('button').toggle(function() {
// case 1: maximize
// ...
another_function($(this));
}, function() {
// case 2: minimize
// ...
another_function($(this));
});
In both toggle cases, the same function is called at the end (another_function()). I would like from that function to find out whether we are in case 1 or in case 2 without having to manipulate the button myself (e.g add a class, set a custom attribute before calling the function, and check on those changes inside the function).
Is there a way to find out from the element state data itself in which toggle case we’re in (surely jQuery must set a state somewhere to know which part of the toggle to execute)?
PS: there are many posts related to that topic already on SO but they’re about hide/show cases and their suggestions (check if it’s visible, hidden…) doesn’t apply here.
You already know what state you are in (maximize/minimize) because the code for that particular state is executing. So you could simply pass this information to
another_functionas an argument:Update: Grovelling jQuery’s internal state
jQuery currently (1.7.2) uses a private back door into the
.data()mechanism to store state for its toggles. This back door is explicitly marked private more than one in the jQuery source and it goes without saying that any part of what follows is subject to change without any notice. Therefore I strongly recommend not going down this path.That said, here’s what’s going on:
jQuery uses a private data space accessed through
$._data()to store the current click count for toggles. This click count modulo 2 is used to decide which function to execute and is incremented on each click.The key used to store this data is currently the string
"lastToggle" + guid, whereguidis a value typically auto-generated by jQuery as well (using a global incrementing counter). The value ofguidis set on the toggle handler functions and you can retrieve it after setting the toggle like this:You can also fix the value of
guidby setting it on the first handler before callingtoggle:Given this handle, you can retrieve the count of clicks so far (and thus predict which handler will be called next) with