jQuery Click Toggle Between Two Functions
Need to execute different actions based on whether an element is clicked once or multiple times? Here's how to achieve it with jQuery:
Built-in .toggle() Method
jQuery offers two .toggle() methods:
Custom Plugin Implementation
As a plugin, this functionality can be implemented as follows:
(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));
Usage
With the plugin, you can call:
$('#test').clickToggle(function() { $(this).animate({ width: "260px" }, 1500); }, function() { $(this).animate({ width: "30px" }, 1500); });
Specific Example
Based on the original question, you can achieve the desired functionality as follows:
var count = 0; $("#time").clickToggle( function() { $(this).animate({ width: "260px" }, 1500); }, function() { $(this).animate({ width: "30px" }, 1500); } );
The above is the detailed content of How to Toggle Between Two Functions on Element Click Using jQuery?. For more information, please follow other related articles on the PHP Chinese website!