Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What to use instead of `toggle(...)` in jQuery > 1.8?

Tags:

jquery

toggle

Now that toggle(...) was deprecated in jQuery 1.8 and then removed in jQuery 1.9

What could be used in general (aside from using the jQuery migrate script) instead of toggle(fn, fn2); thats has the same type of functionality?

Related question (asked about a specific case): What to use instead toggle?


I know that toggle() functionality was not removed, just the ability to add custom toggle functions (aside from the show/hide default functionality).

like image 854
Naftali Avatar asked Jan 17 '13 15:01

Naftali


1 Answers

Here is a simple implementation:

$.fn.toggleClick = function() {
    var methods = arguments;    // Store the passed arguments for future reference
    var count = methods.length; // Cache the number of methods 

    // Use return this to maintain jQuery chainability
    // For each element you bind to
    return this.each(function(i, item){
        // Create a local counter for that element
        var index = 0;

        // Bind a click handler to that element
        $(item).on('click', function() {
            // That when called will apply the 'index'th method to that element
            // the index % count means that we constrain our iterator between 0
            // and (count-1)
            return methods[index++ % count].apply(this, arguments);
        });
    });
};

and use it as

$('selector').toggleClick( function1, function2, ... );
like image 99
Gabriele Petrioli Avatar answered Oct 02 '22 12:10

Gabriele Petrioli