Where has fn.toggle( handler(eventObject), handler(eventObject)…) gone?

Deprecation of jquery .toggle() is now documented at api.jquery.com.
I found a nice replacement for it at forum.jquery that I am now using. It works great 🙂

$.fn.toggleClick = function() {
  var functions = arguments,
      iteration = 0;
  return this.click(function() {
    functions[iteration].call();
    iteration = (iteration + 1) % functions.length;
  });
}

Usage:

$("#target").toggleClick(function() {
  alert( "First handler for .toggle() called." );
}, function() {
  alert( "Second handler for .toggle() called." );
});

Edit Aug. 6, 2014: I reconsidered the original code and found that .apply is not the right thing to use. Changed that to .call with no args passed in.

Leave a Comment