This article expands on and highlights the solution given to a problem outlined in stackflow.
Mootools equivalent of jQuery toggle()?
We have slightly modified the solution provided by Dimitar Christoff to include a reset function. This was essential to a play/pause implementation of this code where are user could select an alternative song which needed to reset the toggled state.
The updated javascript code is:
(function() {
var index = 0;
Element.implement({
toggle: function() {
var args = Array.slice(arguments, 0);
count = args.length - 1;
return this.addEvent('click', function() {
args[index].apply(this, arguments);
index = (count > index) ? index + 1 : 0;
});
},
resetToggle: function() {
index = 0;
}
});
})();
$('play').toggle(
function() {
//Code to implement goes here
}, function() {
//Code to implement goes here
}
);
To reset the toggle simply use
$('play').resetToggle();
When control enters the execution context of a function an arguments object is created.
Angus Croll
You should notice that the arguments object is used in the toggle code. The arguments object is similar to an array, but is not an array. As a result the Array.slice function is used to convert the arguments object into an array. After this has happened the args variable will contain a nice array containing each function as defined in your custom toggle. Try alert(args[0]) to see this in action. Using the index variable the toggle functions simply interates over each function dependent on which function was run last. The resetToggle simply sets the index to 0 to start again.
Note: As the click event is added you do not need to invoke toggle on your own click event.
Thanks to Dimitar Christoff for his work on this.
Update
Dimitar kindly responded with a more up to date version of his original solution. His newer version can be found at: http://jsfiddle.net/VR9k8/5/. Something that is worth noting is that Dimitar's new version requires some mootool's more elements in particular Events.Pseudos and Element.Event.Pseudos. I have decided not to update this article entirely because I believe the short note on the arguments object would be helpful. There is also an argument that the original method above may be suitable as it does not require additional mootools functionality. However, I will leave this one to yourselves, I can see value in both ways.
Please recommend us if you found this article helpful: