Reputation: 19
<script>
function one() {
blah blah blah
}
function two() {
blah blah blah
}
</script>
<button onclick="one(); two()">Click Me</button>
This will call the two functions at the same time. What I want is to call function one() on the first click and then call function two() on the second click. Calls function three() on 3rd click and so on until 7th click
I would prefer to not use jQuery if possible
Upvotes: 0
Views: 8714
Reputation: 28
The simplest way is defining an extra variable to false
(or true
, of course). While our variable is false
, clicking button calls first function and changes the variable to true
. On second click, our onclick function checkes the variable value and calls the function which we defined for true
value.
var button = document.getElementById('button');
var x = false;
button.addEventListener('click', function(){
if(!x){
alert('function 1');
x = true;
}else{
alert('function 2');
x = false;
}
})
Upvotes: 0
Reputation: 114024
One simple way of doing this is to reassign the onclick value:
<button id="clickme">Click Me</button>
<script>
function one() {
alert('one clicked');
document.getElementById('clickme').onclick = two;
}
function two() {
alert('two clicked');
}
document.getElementById('clickme').onclick = one;
</script>
Using this trick you have the option to disable the button after calling two()
:
document.getElementById('clickme').onclick = null;
Toggle the click handler back to one()
:
document.getElementById('clickme').onclick = one;
Or do anything else you want.
Upvotes: 2
Reputation: 39307
You can use an IIFE to accomplish this:
var fn3 = (function() {
var first = true;
return function() {
first ? fn1() : fn2();
first = !first;
}
})();
function fn1() {
console.log(1);
};
function fn2() {
console.log(2);
};
<button onClick="fn3()">click</button>
Upvotes: 6
Reputation: 25882
I'll do it like bellow
On click of the button have a function which decides which function to call according to number of times.
<button onclick="decideFunction()">Click Me</button>
var times = 0;
var one = function(){
alert('first time');
}
var two = function(){
alert('After first');
}
var decideFunction = function(){
if(times == 0){
one();
times++;
}
else{
two();
}
}
So first time it will execute function one
and second time onwards it will execute function two
.
Upvotes: 0
Reputation: 4147
The solution is not too complex, you can just one() and two() from another function.
var callOne = true;
function one() {
alert('Call one');
}
function two() {
alert('Call two');
}
function call(){
if(callOne) one();
else two();
callOne = !callOne;
}
<button onclick="call();">Click Me</button>
Upvotes: 3