Alternative to jQuery's .toggle() method that supports eventData?

Posted by Bungle on Stack Overflow See other posts from Stack Overflow or by Bungle
Published on 2010-03-17T00:29:11Z Indexed on 2010/03/17 0:31 UTC
Read the original article Hit count: 445

The jQuery documentation for the .toggle() method states:

The .toggle() method is provided for convenience. It is relatively straightforward to implement the same behavior by hand, and this can be necessary if the assumptions built into .toggle() prove limiting.

The assumptions built into .toggle have proven limiting for my current task, but the documentation doesn't elaborate on how to implement the same behavior. I need to pass eventData to the handler functions provided to toggle(), but it appears that only .bind() will support this, not .toggle().

My first inclination is to use a flag global to a single handler function to store the click state. In other words, rather than:

$('a').toggle(function() {
  alert('odd number of clicks');
}, function() {
  alert('even number of clicks');
});

do this:

var clicks = true;
$('a').click(function() {
  if (clicks) {
    alert('odd number of clicks');
    clicks = false;
  } else {
    alert('even number of clicks');
    clicks = true;
  }
});

I haven't tested the latter, but I suspect it would work. Is this the best way to do something like this, or is there a better way that I'm missing?

Thanks!

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about javascript-events