Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
148
rated 0 times [  154] [ 6]  / answers: 1 / hits: 21922  / 15 Years ago, wed, march 17, 2010, 12:00:00

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 that's 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?


More From » jquery

 Answers
16

Seems like a reasonable way to do it... I'd just suggest that you make use of jQuery's data storage utilities rather than introducing an extra variable (which could become a headache if you wanted to keep track of a whole bunch of links). So based of your example:



$('a').click(function() {
var clicks = $(this).data('clicks');
if (clicks) {
alert('odd number of clicks');
} else {
alert('even number of clicks');
}
$(this).data(clicks, !clicks);
});

[#97317] Sunday, March 14, 2010, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
louiemarvinm

Total Points: 473
Total Questions: 103
Total Answers: 94

Location: Samoa
Member since Mon, Nov 8, 2021
3 Years ago
;