Home >Web Front-end >JS Tutorial >How to Toggle Between Two Functions on Element Click Using jQuery?

How to Toggle Between Two Functions on Element Click Using jQuery?

Barbara Streisand
Barbara StreisandOriginal
2024-11-09 01:42:02667browse

How to Toggle Between Two Functions on Element Click Using jQuery?

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:

  • One method toggles the visibility of elements.
  • A deprecated method (removed in jQuery 1.9) called toggle(func1, func2) efficiently handles toggling between two functions on element click.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn