Alternate two functions when pressed

How can I alternate a call to two functions when pressed? For example, here is a button

<div id="fooButton" />

and here is javascript

function fooOne() {
     alert('foo One called');
}

function fooTwo() {
     alert('foo Two called');
}

How do I call fooOne () and fooTwo () on alternative button presses?

+3
source share
2 answers

You can use toggle pseudo-event :

$('#fooButton').toggle(fooOne, fooTwo);

Note. This is deprecated from jQuery 1.8 and is removed in jQuery 1.9+. You can use jQuery-migrate if you still need this function.

+11
source

Use jQuery toggle () method

$("#fooButton").toggle(fooOne, fooTwo);

Edited to use your named functions, not sloppily using anonymous ones.

+6
source

All Articles