Home >Web Front-end >JS Tutorial >How to Alternate Function Calls on Click Events?
Question:
How can I execute different functions when an element is clicked, alternating between them with each successive click?
Answer:
jQuery offers an alternate version of the .toggle() method specifically designed for this purpose, although it has since been deprecated. There are alternative approaches, such as creating a custom plugin that provides the desired functionality.
Using the Deprecated .toggle() Method:
$('#element').toggle(function() { // Function 1 }, function() { // Function 2 });
Custom Plugin:
(function($) { $.fn.clickToggle = function(func1, func2) { var funcs = [func1, func2]; this.data('toggleclicked', 0); this.click(function() { var data = $(this).data(); var tc = data.toggleclicked; $.proxy(funcs[tc], this)(); data.toggleclicked = (tc + 1) % 2; }); return this; }; }(jQuery)); $('#element').clickToggle(function() { // Function 1 }, function() { // Function 2 });
Notes:
The above is the detailed content of How to Alternate Function Calls on Click Events?. For more information, please follow other related articles on the PHP Chinese website!